1. 界面重复创建的问题
2. 中间容器每次切换,都会清空容器中的子对象问题
3. 点击返回键的处理
解决重复创建的问题:
传递Class字节码对象,利用泛型来规定对象
判断界面是否存在,如果存在重复使用,如果不存在,创建;记录当前正在展示的界面
MainActivity.java
/** * 初始化主体 */ public void initMiddle() { mainContainer=(RelativeLayout) findViewById(R.id.il_main); MiddleManager.getInstance().setMainContainer(mainContainer); MiddleManager.getInstance().loadView(LoginView.class); }
MiddleManager.java
package com.tsh.lottery.views; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; import android.content.Context; import android.view.View; import android.view.animation.AnimationUtils; import android.widget.RelativeLayout; import com.tsh.lottery.R; public class MiddleManager { private RelativeLayout mainContainer; //单例 private static MiddleManager manager=new MiddleManager(); private MiddleManager(){}; public static MiddleManager getInstance(){ return manager; } public void setMainContainer(RelativeLayout mainContainer) { this.mainContainer = mainContainer; } //界面缓存 private Map<String,BaseView> VIEWCACHE=new HashMap<String,BaseView>(); //当前界面 private BaseView currentView; /** * 加载界面 */ public void loadView(Class<? extends BaseView> baseViewClass) { BaseView baseView=null; //判断是否存在 String key=baseViewClass.getSimpleName(); if(VIEWCACHE.containsKey(key)){ baseView=VIEWCACHE.get(key); }else{ try { Constructor<? extends BaseView> constructor; constructor = baseViewClass.getConstructor(Context.class); baseView=constructor.newInstance(mainContainer.getContext()); } catch (Exception e) { e.printStackTrace(); } VIEWCACHE.put(key, baseView); } mainContainer.removeAllViews(); // if(currentView!=null){ // SlideUtil.slideOut(currentView.getView(), 2000); // } View child=baseView.getView(); mainContainer.addView(child); //SlideUtil.slideIn(child, 2000); child.startAnimation(AnimationUtils.loadAnimation(mainContainer.getContext(), R.anim.left_to_right)); currentView=baseView; } }
IndexView.java
package com.tsh.lottery.views; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.TextView; /** * 会员界面 * @author taoshihan * */ public class IndexView extends BaseView{ private TextView textView; /** * 构造函数 * 经过之前的处理,这个构造函数只会执行一次 * @param context */ public IndexView(Context context) { super(context); initView(); } /** * 初始化界面 */ private void initView() { textView=new TextView(context); LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); textView.setLayoutParams(params); textView.setText("我是会员界面"); } @Override public View getView() { return textView; } }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/5384.html