如何在一个activity中更改另一个activity的UI了,如更改另一个activity中按钮的背景图片。
在这里,我上网搜了一些资料,使用Handler共享数据,以达到其效果。
代码:
被修改UI的activity:
package mark.zhang;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MasterActivity extends Activity {
// 用于msg.what值
private static final int CHANGED = 0x0010;
private Button btn_to = null;
private TextView tv = null;
private MyHandler handler = null;
private MyAPP mAPP = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAPP = (MyAPP) getApplication();
handler = new MyHandler();
tv = (TextView) findViewById(R.id.tv);
btn_to = (Button) findViewById(R.id.btn_to);
// 设置监听器
btn_to.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 设置共享变量
mAPP.setHandler(handler);
// 启动另一个Activity
Intent intent = new Intent(MasterActivity.this,
ToChangeViewActivity.class);
startActivity(intent);
}
});
}
/**
* 自己实现 Handler 处理消息更新UI
*
* @author mark
*/
final class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == CHANGED) { // 更新UI
tv.setText("changed after: I have be changed by Other Activity!");
tv.setBackgroundColor(Color.BLUE);
btn_to.setText("I have been changed!");
btn_to.setBackgroundColor(Color.RED);
}
}
}
}
发出更改UI消息的activity:
package mark.zhang;
import mark.zhang.MasterActivity.MyHandler;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class ToChangeViewActivity extends Activity {
private static final int CHANGED = 0x0010;
private MyAPP mAPP = null;
private MyHandler mHandler = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
mAPP = (MyAPP) getApplication();
// 获得该共享变量实例
mHandler = mAPP.getHandler();
findViewById(R.id.btn_chang).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 发送消息
mHandler.sendEmptyMessage(CHANGED);
ToChangeViewActivity.this.finish();
}
});
}
}
3.必须实现继承Application实现跨activity共享:
package mark.zhang;
import mark.zhang.MasterActivity.MyHandler;
import android.app.Application;
/**
* 自己实现Application,实现数据共享
*
* @author mark
*
*/
public class MyAPP extends Application {
// 共享变量
private MyHandler handler = null;
// set方法
public void setHandler(MyHandler handler) {
this.handler = handler;
}
// get方法
public MyHandler getHandler() {
return handler;
}
}