当我去运行应用程序时,一切似乎都很好但是当我按下“开始”按钮时它不会显示Hello我甚至尝试在线程之前设置文本并且它仍然无法正常工作。为什么会发生这种情况?
以下是代码:
public class MainActivity extends Activity implements OnClickListener {
Handler mHandler;
Button enter;
Button start;
TextView显示;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enter = (Button)findViewById(R.id.enter);
start = (Button)findViewById(R.id.start);
display =(TextView)findViewById(R.id.Display);
mHandler = new Handler(){
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Bundle bundle = msg.getData();
String string = bundle.getString("myKey");
display.setText(string);
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.enter:
break;
case R.id.start:
Thread setText = new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
Message msg= Message.obtain();
Bundle bundle = new Bundle();
String dateString;
dateString = "Hello";
bundle.putString("myKey", dateString);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
};
setText.start();
break;
}
}
}
答案 0 :(得分:1)
您没有在onCreate()方法的enter / start按钮上注册Listeners。只需拨打电话:
enter.setOnClickListener(this);