记录用户点击的操作历史,使用栈数据结构,频繁的操作栈顶(添加,获取,删除),使用LinkedList
捕获用户的返回键操作,响应返回键,返回上一个界面
MainActivity.java
/** * 返回键处理 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK){ boolean result=MiddleManager.getInstance().goBack(); if(!result){ Toast.makeText(MainActivity.this, "是否退出应用", 1).show(); } return false; } return super.onKeyDown(keyCode, event); }
MiddleManager.java
//操作历史栈 private LinkedList<String> HISTORY=new LinkedList<String>(); /** * 处理返回键 * @return */ public boolean goBack() { //如果为空会抛异常 if(HISTORY.size()>0){ if(HISTORY.size()==1){ return false; } HISTORY.removeFirst(); if(HISTORY.size()>0){ String key=HISTORY.getFirst(); BaseView targetView=VIEWCACHE.get(key); mainContainer.removeAllViews(); View child=targetView.getView(); mainContainer.addView(child); child.startAnimation(AnimationUtils.loadAnimation(mainContainer.getContext(), R.anim.left_to_right)); currentView=targetView; return true; } } return false; }
/** * 加载界面 */ 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(); View child=baseView.getView(); mainContainer.addView(child); child.startAnimation(AnimationUtils.loadAnimation(mainContainer.getContext(), R.anim.left_to_right)); currentView=baseView; //放入栈 HISTORY.addFirst(key); }