Message Handler Looper

//布局文件



    

//Activity
//Android不允许子线程操作UI
//注意:类必须实现implements View.OnClickListene

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:
                    //在这里可以进行UI操作
                    text.setText("Nice to meet you");
                    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_text);
        Log.d("123","findViewById button");
        changeText.setOnClickListener((View.OnClickListener) this);
    }

    public void onClick(View v){
        switch (v.getId()){
            case R.id.change_text:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = UPDATE_TEXT;
                        handler.sendMessage(message);
                    }
                }).start();
                break;
            default:
                break;

        }
    }
}

你可能感兴趣的:(Message Handler Looper)