• Handler机制post方法使用


    public class MainActivity extends Activity {
          private TextView tv;
      private Button button;
      private Handler handler = new Handler();
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.buttonId);
        tv = (TextView)findViewById(R.id.textViewId);
        button.setOnClickListener(new MyButton());
      }
      class MyButton implements OnClickListener {
        @Override
        public void onClick(View v) {
          Thread t = new MyThread();
          t.start();
        }
      }
      class MyThread extends Thread {
        @Override
        public void run() {
          Runnable runnable = new Runnable() {
            @Override
            public void run() {
              //比如这里从网络中获取到了数据吗,在这里直接可以更新主线程中的数据
              String currentString = Thread.currentThread().getName();
              System.out.println("当前线程的名称为:"+currentString);
              tv.setText(currentString);
            }
          };
          handler.post(runnable);
        }
      }
    }

    post机制将runnable对象运行在主线程中的

  • 相关阅读:
    [CC-TRIPS]Children Trips
    [HDU5968]异或密码
    [CC-PERMUTE]Just Some Permutations 3
    [HackerRank]Choosing White Balls
    Gym102586L Yosupo's Algorithm
    Gym102586B Evacuation
    Kattis anothercoinweighingpuzzle Another Coin Weighing Puzzle
    Gym102586I Amidakuji
    CF1055F Tree and XOR
    CF241B Friends
  • 原文地址:https://www.cnblogs.com/zhangkefan/p/4774375.html
Copyright © 2020-2023  润新知