数据更新的基本写法

private TextView tv;
private Button btn,btn2;
private int btnsend;
private final int HANDLER_TEST=1;
private final int HANDLER_STOP=0;
private int count=0;

private Handler handler=new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);

// Toast.makeText(MainActivity.this, count, 500).show();
switch (msg.what) {
case HANDLER_TEST :
tv.setText("当前计数值:"+count);
break;

default:
break;
}

}

};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.Tv);
btn=(Button)findViewById(R.id.button);
btn2=(Button)findViewById(R.id.button2);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
btnsend=HANDLER_TEST;
}

});

btn2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
btnsend=HANDLER_STOP;
}

});


new Thread(new Runnable() {

@Override
public void run() {
while(true){
try {

Thread.sleep(10);
count++;
System.out.println(count);
// btnsend=HANDLER_TEST;
} catch (Exception e) {
e.printStackTrace();
}
Message msg=new Message();
msg.what=btnsend;
handler.sendMessage(msg);

}
}
}).start();
}

原文地址:https://www.cnblogs.com/liumin-txgt/p/13050589.html