Handler小例子,更换按钮的背景颜色

来源:互联网 发布:鄂州软件开发 编辑:程序博客网 时间:2024/06/04 18:26

     这几天一直在忙着开发一个新项目,写代码写得昏天黑地的,今天抽了几分钟时间写了下极简单的例子,改天有时间再写啦!

布局文件很简单,就一个Button:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

   <Button
        android:id="@+id/handler_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:text="ColorButton"/>

</RelativeLayout>

主界面代码,有详细的注释:
public class MainActivity extends Activity {
/**按钮*/
private Button btn;
/** 更新UI主线程对象 */
private Handler handler = new Handler() {
/** 异步接受消息 */
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
/** 获取Map数据 */
Bundle bundle = msg.getData();
/** 取得颜色值 */
int color = bundle.getInt("color");
MainActivity.this.btn.setBackgroundColor(color);//更新按钮的背景颜色
}


};


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.btn = (Button) findViewById(R.id.handler_btn);
btn.setOnClickListener(new btnOnClickListener());
}


class btnOnClickListener implements OnClickListener {
public void onClick(View v) {
MyThread my = new MyThread();
/**启动线程 */
new Thread(my).start();
}
};


class MyThread implements Runnable {


public void run() {
try {
Thread.sleep(3000);// 子线程睡眠3秒
} catch (InterruptedException e) {
e.printStackTrace();
}
/**发消息 */
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putInt("color", Color.RED);
msg.setData(bundle);
/**发送消息,通知主线程更新 */
MainActivity.this.handler.sendMessage(msg);
}
};
}

0 0
原创粉丝点击