Android 纯代码化编码2_基本控件

关于这个,我目前研究的控件还比较少,因为基本大操作方式都大同小异,搞清楚几个就差不多,至于其他,那只是时间问题

1.文本标签,文本输入框

 

TextView label = new TextView(this);
label.setText("名称:");
// 默认字体大小为16
label.setTextSize(16);
// 颜色默认为黑色
label.setTextColor(Color.BLACK);
// 创建输入框对象
EditText text = new EditText(this);
// 默认设置为单行显示
text.setSingleLine();
// 默认宽度为150
text.setWidth(150);
// 默认字体大小为16
text.setTextSize(16);
text.setTextColor(Color.BLACK);
// 如果配置了最大长度,那么进行设置
text.setFilters(new InputFilter[] { new InputFilter.LengthFilter(20) });
// 设置内容展示为密码形式
text.setTransformationMethod(new PasswordTransformationMethod());

 

2.按钮

Button button = new Button(this);
button.setText("提交");
button.setTextSize(16);
button.setTextColor(Color.BLACK);

 3.按钮事件
为按钮增加事件,我相信这很简单,但是在安卓中,这里就存在一个问题,安卓不允许是主线程中执行耗时操作(例如从服务器上下载一个东西到本地),如果使用会发生异常:

Can't create handler inside thread that has not called Looper.prepare()
所以只能使用新的线程去操作,但是在非UI线程中,操作UI线程的东西又会报异常,这个很迷惑了我一些时间,后来通过在网上查找资料,最终总结出一种较为方便的办法,使用AsyncTask

button.setOnClickListener(new OnClickListener() {
	public void onClick(View v) {
		// 定义一个异步任务处理对象,定义在下面
		ButtonAsyncTask asyncTask = new ButtonAsyncTask();
		// 执行这里的时候会依次调用下面的
		// onPreExecute(同步)--> doInBackground(异步)--> onPostExecute(同步)
		asyncTask.execute();
	}

});
	
/**
 * 按钮的异步执行机制
 * 
 * @author pandong
 * @date 2012-7-18 下午2:50:31
 * @Copyright(c) SZKINGDOM
 */
private class ButtonAsyncTask extends AsyncTask<Void, Void, Object> {
	@Override
	protected void onPreExecute() {
		//在同步线程中执行的代码
	}
	@Override
	protected Object doInBackground(Void... params) {
		//在异步线程中执行某些代码
		return null;
	}
	@Override
	protected void onPostExecute(Object result) {
		//执行完后需要执行的代码
	}
}
 

你可能感兴趣的:(android,安卓)