在一个Activity中使用多个View
如果把Activity看作MVC中的Control?它负责管理UI和接受事件(包括用户的输入),虽然说一个Activity通常对应一个屏幕,但事实上,我们是可以只用一个Activity管理多个不同的View来实现简单的逻辑。首先,我们增加一个新的资源描述layout/second.xml。<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView id="@+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello 中国" />
<Button id="@+id/go2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back">
<requestFocus />
</Button>
</LinearLayout>
除了一个“Hello中国”以外,增加一个按钮可以返回前一个界面。然后,在代码中我们要为HelloTwo(工程名字)增加两个方法,setViewOneCommand和setViewTwoCommand,分别处理一下在不同界面时,从资源里加载组件并为组件绑定一个事件处理器。
public void setViewOneCommand() {
Button btn = (Button)findViewById(R.id.go);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
helloTwo.this.setContentView(R.layout.second);
helloTwo.this.setViewTwoCommand();
}
});
Button btnExit=(Button)findViewById(R.id.exit);
btnExit.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
helloTwo.this.finish();
}
});
}
public void setViewTwoCommand() {
Button btnBack=(Button)findViewById(R.id.go2);
btnBack.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
helloTwo.this.setContentView(R.layout.main);
helloTwo.this.setViewOneCommand();
}
});
}
最后,我们需要在onCreate的时候,也就是启动后的main界面上设置一下按钮事件处理器。新的onCreate方法如下:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setTheme(android.R.style.Theme_Dark);
setContentView(R.layout.main);
setViewOneCommand();
}
编译,运行,OK。
可能是代码 编辑器有点问题,使代码显示不出来,所以从新编辑就没用编辑器,直接贴代码。