本文主要是介绍安卓篇:消息和UI,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在Android中,在非主线程中更新UI控件是不安全的,app在运行时会直接Crash,所以当我们需要在非主线程中更新UI控件,那么就需要用到Handler和Message来实现
Demo中,使用到一个按钮和一个TextView,点击按钮之后改变TextView的内容,按钮点击时候新建一个进程,在进程中对UI控件进行修改。
initHandler();
private void initHandler()
{
final View child[][] = new View[10][10];
final View child1[][] = new View[10][10];
mHandler = new Handler(){
@SuppressWarnings({ "deprecation", "unused" })
@Override
public void handleMessage(Message msg) {
if(msg.what == alarm_selected_cleared) //清除报警器选择状态
//clear_alarm_selected();
{
Log.e("", "alarm_selected_cleared");
return;
}
for(int i = 0; i<getCarNum(); i++)
{
for(int j = 0 ; j< getAlarmNum() ;j++)
{
if(((View)MyView[i].getChildAt(2*j) == null)|| ((View)MyView[i].getChildAt(2*j+1) == null))
{
Log.e("", "OVER! ");
return;
}
int childcount = MyView[i].getChildCount();
child[i][j] = (View)MyView[i].getChildAt(2*j);
child1[i][j] = (View)MyView[i].getChildAt(2*j+1);
if(msg.what == alarm_selected_changed_sta[i][j])
{
Log.e("", "A: "+i+" B: "+j+" "+ alarm_selected_changed_sta[i][j]);
filck_control.startFlick(child[i][j], 300);
child[i][j].setBackgroundDrawable(getResources().getDrawable(R.drawable.alarm_active));
break;
}
if(msg.what == alarm_selected_changed_sta[i][j+10])
{
Log.e("", "AA: "+i+" BB: "+j+" "+ alarm_selected_changed_sta[i][j+10]);
clear_select_sta();
child1[i][j].setBackgroundDrawable(getResources().getDrawable(R.drawable.alarm_selected));
}
}
}
}
};
}
然后,通过发送消息更新界面。
static public MyViewGroup tab_fragment_passenger_alarm;
public class MyFlashThread extends Thread {
//继承Thread类,并改写其run方法
private final static String TAG = "My Thread ===> ";
public void run(){
Log.d(TAG, "run");
for(int i = 0; i<5000; i++)
{
if((i%6 ==3)||(i%6 ==4))
{
try {
Thread.sleep(500);
MainActivity.tab_fragment_passenger_alarm.mHandler.sendEmptyMessage(MyViewGroup.alarm_selected_changed_sta[i%6][i%6+1]);
MainActivity.tab_fragment_passenger_alarm.mHandler.sendEmptyMessage(MyViewGroup.alarm_selected_changed_sta[i%6][i%6]);
} catch (InterruptedException e) {
e.printStackTrace(); }
}
else
{
try {
Thread.sleep(500);
//MainActivity.tab_fragment_passenger_alarm.mHandler.sendEmptyMessage(MyViewGroup.alarm_selected_changed);
} catch (InterruptedException e) {
e.printStackTrace(); }
}
}
}
}
这篇关于安卓篇:消息和UI的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!