(Thread)子线程不能操作UI线程

解决方法:
https://www.jianshu.com/p/59aaf7b1c9e5

布局文件

<?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>

Acitvity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView text;
    @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);

    }

    public void onClick(View v){
        switch (v.getId()){

            case R.id.btn_change_text:
                new Thread(new Runnable(){
                    public void run(){
                        text.setText("Nice to meet you");
                    }
                }).start();
                break;
                default:
                    break;

        }

    }
}

需要注意:
1、 需要实现implements View.OnClickListener


image.png
image.png

解决方法:Android中的异步消息处理

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 178,812评论 25 709
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 13,918评论 2 59
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    wgl0419阅读 6,568评论 1 9
  • 每时每刻的天空都是不一样的 哪怕有时候肉眼看到的天空是一样的 但在我们看不到的地方 呈现的是不同的 就像人生 没有...
    李鱼菡萏阅读 381评论 6 5
  • 2018年10月19号,今天中午去接她,一放学就和我说数学今天考试了,我问她这次考的怎么样?还自信满满的说都会做,...
    董依晴妈妈阅读 176评论 0 0

友情链接更多精彩内容