在一个Activity中使用多个View (可以借鉴的一种思路)

在一个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。


可能是代码 编辑器有点问题,使代码显示不出来,所以从新编辑就没用编辑器,直接贴代码。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值