0
回答
当时遇到的主要难点在于TextView的内容不会刷新改变值,今天终于通过Timer和Handler实现了,分享给大家
华为云实践训练营,热门技术免费实践!>>>   
import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.TextView; public class AndroidLuckyActivity extends Activity{ private TextView textView; private Button button_start; private Button button_end; private Boolean begined = false ; private Timer timer; private Handler handler; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); init(); handler = new Handler() { public void handleMessage(Message msg) { super .handleMessage(msg); if(begined == true ) { textView.setText("" + msg.what); } else if(begined == false ) {                    textView.setText("" + msg.what); timer.cancel(); // Timer停止 } } }; } void init() { textView = (TextView) this .findViewById(R.id.tv); button_start = (Button) this .findViewById(R.id.btn_start); button_end = (Button) this .findViewById(R.id.btn_end); button_start.setOnClickListener( new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub begined = true ; button_start.setEnabled( false ); button_end.setEnabled( true ); timer = new Timer(); timer.schedule( new TimerTask() { @Override public void run() { // TODO Auto-generated method stub Message message = new Message(); message.what = ( int) (Math.random() * 999 + 100 ); handler.sendMessage(message); } }, 1000, 30); // 从1000ms即1s开始,30ms为数字改变周期 } }); button_end.setOnClickListener( new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub begined = false ; button_start.setEnabled( true ); button_end.setEnabled( false ); } }); }}

运行图:


原文链接:http://www.cnblogs.com/vus520/archive/2012/02/15/2561966.html
<无标签>
举报
长平狐
发帖于5年前 0回/86阅
顶部