本文演示一个在同一个Activity中切换显示不同View的例子。先创建一个ViewStackActivity类,负责管理并缓存View。贴代码为上:
public abstract class ViewStackActivity extends Activity { AbstractMap<Integer, View> views = new HashMap<Integer, View>(); /** * @see android.app.Activity#onCreate(Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.loadViews(this.getViewIds()); } void loadViews(int[] ids) { LayoutInflater flater = this.getLayoutInflater(); for (int i=0; i<ids.length; ++i) { View view = flater.inflate(ids[i], null); this.OnViewCreated(ids[i], view); views.put(new Integer(ids[i]), view); } } public abstract int[] getViewIds(); public abstract void OnViewCreated(int id, View view); void loadView(int id) { View view = this.getLayoutInflater().inflate(id, null); this.OnViewCreated(id, view); views.put(new Integer(id), view); } void setActiveView(int id) { View view = views.get(new Integer(id)); if (view == null) { Toast.makeText(this, "View id: " + id + " not found.", Toast.LENGTH_SHORT).show(); return; } this.setContentView(view); } }
ViewStackActivity类有两个抽象函数getViewIds和OnViewCreated需要其子类实现。前者用于获取view id数组,后者用于首次实例化View时做些初始化工作。实际使用例子:
public class MainActivity extends ViewStackActivity { /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setActiveView(R.layout.viewstack1); } @Override public int[] getViewIds() { return new int[] { R.layout.viewstack1, R.layout.viewstack2}; } @Override public void OnViewCreated(int id, View view) { if (id == R.layout.viewstack1) { Button btn1 = (Button) view.findViewById(R.id.Button01); btn1.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { Toast.makeText(getBaseContext(), "Click Button02 to switch to another view...", Toast.LENGTH_SHORT).show(); } }); Button btn2 = (Button) view.findViewById(R.id.Button02); btn2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { setActiveView(R.layout.viewstack2); } }); } else if (id == R.layout.viewstack2) { Button btn1 = (Button) view.findViewById(R.id.Button01); btn1.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { setActiveView(R.layout.viewstack1); } }); } } }
资源id定义见下载包。
小结:本文给出一个用于View切换的ViewStackActivity类,根据论坛中的一个帖子的需求而作。View的组织方式千变万化,把View集中在一个Activity中可能不是好的选择,尤其是切换的View间相关性不高时简单的堆砌在一起将增加日后维护的复杂度。
附下载包:ViewStackEx.7z