温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android 使用xml和java混合编写ui

发布时间:2020-08-06 02:43:14 来源:网络 阅读:849 作者:无用大叔 栏目:移动开发

以一个简单的图片浏览器实例说明


新建工程后:

    在activit_main.xml中添加代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
</LinearLayout>

在java中添加代码:

public class MainActivity extends Activity {

	int[] p_w_picpath = new int[] {
			R.drawable.p1,
			R.drawable.p2,
			R.drawable.p3,
			R.drawable.p4
	};
	ImageView myp_w_picpath;
	int curImage = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		LinearLayout layout = (LinearLayout)this.findViewById(R.id.main);
		myp_w_picpath = new ImageView(this);
		layout.addView(myp_w_picpath);
		myp_w_picpath.setImageResource(p_w_picpath[0]);
		myp_w_picpath.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				myp_w_picpath.setImageResource(p_w_picpath[++curImage%p_w_picpath.length]);
			}
			
		});
	}


在Android中,每一个组件的性质可以在.xml中定义,同时每个性质都有对应的java方法

注意:以上代码中 使用java代码添加新的组件,可把声明写在类中,但是他必须被赋值为一个new在onCreate()内部的对象,否则程序会出错,究其原因是因为在java中添加组件的时候必须初始化的时候加入参数(this)



向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI