我无法理解为什么我的后台线程在屏幕方向更改后无法更改 textView( txtName ) 的内容。
如果我将txtname设为静态,它可以工作,但没有静态它不起作用。它只是其初始值没有被后台线程更新。
private TextView txtName;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
txtName = (TextView) findViewById(R.id.txtName);
TextView txtEmail = (TextView) findViewById(R.id.txtEmail);
Button btnClose = (Button) findViewById(R.id.btnClose);
Button btnBack = (Button) findViewById(R.id.btnBack);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String email = i.getStringExtra("email");
// String data = i.getStringExtra("data");
// Displaying Received data
txtName.setText("HI");
txtEmail.setText(email);
// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
Thread background = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 30; i++) {
try {
Thread.sleep(1000);
Message msg = new Message();
Bundle b = new Bundle();
b.putString("My Key", "My Value: " + String.valueOf(i));
msg.setData(b);
// send message to the handler with the current message handler
handler.sendMessage(msg);
Log.e("Error", "IN THREAD");
} catch (Exception e) {
Log.d("Error", e.toString());
}
}
}
});
background.start();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = getIntent();
returnIntent.putExtra("returnResult","i want to back page.");
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
// get the bundle and extract data by key
Bundle b = msg.getData();
String key = b.getString("My Key");
txtName.setText( "Item " + key);
txtName.setVisibility(View.VISIBLE);
Log.e("TEST MESSAGE", txtName.getText().toString());
}
};