您的位置:首页 > 产品设计 > UI/UE

安卓开发笔记(十九):异步消息处理机制实现更新软件UI

2019-03-31 21:07 639 查看
版权声明:本文章由Geek Song创造,转载请注明链接,作者。否则必追求法律责任。 https://blog.csdn.net/Geeksongs/article/details/89038422

安卓开发笔记(十九):异步消息处理机制实现更新软件UI

主界面代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/change"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="改变内容"/>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="你好,世界!"
android:textSize="20sp"/>

</RelativeLayout>

主活动代码:

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView text;
public static final int UPDATE_TEXT=1;
private Handler handler=new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case UPDATE_TEXT:
text.setText("遇见你真好");
break;
default:
break;

}
}

};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(TextView)findViewById(R.id.text);
Button ChangeText=(Button)findViewById(R.id.change);
ChangeText.setOnClickListener(this);
}
public void onClick(View v)
{
switch (v.getId())
{
case R.id.change:
new Thread(new Runnable() {
@Override
public void run() {
Message message=new Message();
message.what=UPDATE_TEXT;
handler.sendMessage(message);

}
}).start();
break;
default:
break;
}

}
}

 

posted @ 2019-03-31 21:07 Geeksongs 阅读(...) 评论(...) 编辑 收藏
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: