美文网首页
[代码]_[后台线程]_[demo1]

[代码]_[后台线程]_[demo1]

作者: 勤学奋进小郎君 | 来源:发表于2018-08-20 21:02 被阅读0次
    public class MainActivity extends AppCompatActivity {
    
        private TextView text;
        private Button bt;
        private int number = 1;
        private Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg){
                switch (msg.what){
                    case 1:
                        text = (TextView)findViewById(R.id.text);
                        text.setText(String.valueOf(msg.arg1));
                        break;
                }
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            bt = (Button)findViewById(R.id.button);
            bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Thread(new Runnable(){
    
                        @Override
                        public void run() {
                            for (int number = 0; number < 10; number++){
                                Message msg = new Message();
                                msg.what = 1;
                                msg.arg1 = number;
                                handler.sendMessage(msg);
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }).start();
    
                }
            });
    
    
        }
    
    }
    

    相关文章

      网友评论

          本文标题:[代码]_[后台线程]_[demo1]

          本文链接:https://www.haomeiwen.com/subject/gukriftx.html