布局文件
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hzx.androidthreadtest.MainActivity">
<Button
android:id="@+id/btn_change_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Change Text"/>
<TextView
android:id="@+id/show_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello world"
android:textSize="25sp"/>
</RelativeLayout>
Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int UPDATE_TEXT = 1;
private TextView text;
private int put_count = 0;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.show_text);
//Button btn_change_text = (Button)findViewById(R.id.btn_change_text);
//btn_change_text.setOnClickListener((View.OnClickListener) MainActivity.this);
findViewById(R.id.btn_change_text).setOnClickListener((View.OnClickListener) this);
handler = new MyHandler();
}
public void onClick(View v){
Message message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
Log.d("123","点击");
}
class MyHandler extends Handler{
public void handleMessage(Message msg){
switch (msg.what){
case UPDATE_TEXT:
//在这里可以进行UI操作
put_count++;
text.setText("Nice to meet you! count:"+put_count);
break;
}
}
}
}
效果