记录用户点击的操作历史,使用栈数据结构,频繁的操作栈顶(添加,获取,删除),使用LinkedList
捕获用户的返回键操作,响应返回键,返回上一个界面
MainActivity.java
/*** 返回键处理*/@Overridepublic 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);}
以上所述是小编给大家介绍的Android实现返回键功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!
新闻热点
疑难解答