记录用户点击的操作历史,使用栈数据结构,频繁的操作栈顶(添加,获取,删除),使用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>();
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中LinearLayoutManager一键返回顶部示例Android实现点击两次返回键退出在Unity中捕捉Android的常用按钮返回事件Android实现返回键功能Android点击按钮返回顶部实现代码