我正在尝试使用Handler更改EditText的内容。
我已经定义了自己的Application类,名为MyApp。我自己的Activity,名为MyActivity。我自己的Handler,名为MyHandler。
MyApp中的回调方法用于确定何时更改MyActivity中EditText的内容。 MyHandler处理来自MyApp的消息,并调用MyMctivity中定义的setMessage函数来更改EditText的内容。
这是我的代码。当应用程序第一次运行时,一切都很好。然后我退出应用程序并重新打开它,当调用setMessage函数时,只显示Toast,而消息(EditText)为空。似乎messages.setText不起作用。但是消息的ID(EditText)就是应用程序第一次运行时的ID。并且message(String)不为空。
MyApp的:
public class MyApp extends Application {
private MyHandler handler;
@Override
public void onCreate() {
super.onCreate();
handler = new MyHandler();
init();
}
public MyHandler getHandler() {
return handler;
}
...
public class MyCallback extends OtherCallback {
...
@Override
public void onReceiveMessage(String content, String alias, String topic) {
Message message = handler.obtainMessage(R.id.receive, content);
message.sendToTarget();
}
...
}
}
MyHandler的:
public class MyHandler extends Handler {
private MyActivity myActivity;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case R.id.receive:
if (myActivity != null) {
myActivity.setMessage((String) msg.obj);
}
break;
case R.id.register:
...
break;
default:
super.handleMessage(msg);
break;
}
}
public void setActivity(MyActivity activity) {
if (myActivity == null) {
this.myActivity = activity;
}
}
}
MyActivity:
public class MyActivity extends Activity {
private EditText messages;
MyApp app;
MyHandler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messages = (EditText) findViewById(R.id.messages);
app = (MyApp) getApplication();
handler = app.getHandler();
handler.setActivity(this);
}
public void setMessage(String message) {
messages.setText(message);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}