Android Handler练习

 package com.example.myact12;

 import java.util.Random;

 import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Android handler
* @Describe:
* @package: com.example.myact12
* @author shaobn
* @date 2015-9-16 上午10:11:50
*/
public class MainActivity extends ActionBarActivity {
private Button start;
private Button end;
private TextView textView;
private Handler handler = new Handler(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) this.findViewById(R.id.button1);
end = (Button) this.findViewById(R.id.button2);
textView = (TextView) this.findViewById(R.id.textView1);
start.setOnClickListener(new ButtonClick());
end.setOnClickListener(new ButtonClick());
}
class ButtonClick implements View.OnClickListener{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.button1:
Runnable runnable = new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
Random random = new Random();
final int num = random.nextInt(100);
Runnable runnable2 = new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} MainActivity.this.textView.setText(String.valueOf(num));
}
}; MainActivity.this.handler.post(runnable2);
}
};
new Thread(runnable).start();
break; case R.id.button2:
Runnable runnable2 = new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub }
};
break;
} } }
}
上一篇:MySQL 一些查询语句及技巧


下一篇:Android Handler的使用