我想为我的片段构建自定义历史堆栈。我已经实现了逻辑来显示和隐藏它们(无论它们的总数)。现在我希望能够根据要求(下面的场景)按下并返回到前一个。
让我们说我们有4个视图(片段):A,B,C和D.每次看到x - >这意味着从x按下按钮转到y。这就是我想要的:
到目前为止,我已经创建了一个存储整数的堆栈viewManager = new Stack<>();
(在父活动中)(每个整数代表我的一个视图A,B,C和D)。我的想法是,每次我添加一个视图并将其整数添加到堆栈。
这是我的addViewToStack方法:
public final void addViewToStack(Integer theView){
//if empty
if(viewManager == null)
viewManager = new Stack<>();
//if it has no view add the current view
if(viewManager.size() == 0) {
viewManager.push(Integer.valueOf(theView));
return;
}
//if the view is already at the top, do nothing
if(viewManager.peek() == Integer.valueOf(theView))
return;
else {
int viewPosition = viewManager.indexOf(Integer.valueOf(theView));
if(viewPosition == -1) { //if not found in the stack
viewManager.push(Integer.valueOf(theView));
}
else{ //if already in the stack we remove all the elements above
while (viewManager.size() > 0) {
if (viewPosition < viewManager.size() -1 )
viewManager.pop();
else //we reached the element
return;
}
}
}
}
然后,这是pressBack方法:
public final void pressBack(){
if(viewManager == null || viewManager.isEmpty())
throw new IndexOutOfBoundsException("The view manager is null or empty. You must have at least two fragments before calling pressBack()");
viewManager.pop();
changeView(viewManager.peek());
}
还有changeView方法:
public void changeView(int destination){
switch (destination) {
case VIEW_A_ID:
//launch the view
break;
case VIEW_B_ID:
//launch the view
break;
case VIEW_C_ID:
//launch the view
break;
case VIEW_D_ID:
//launch the view
break;
default:
//do nothing
break;
}
addViewToStack(destination);
}
现在的问题是,有时我会向我抛出IndexOutOfBoundsException。你能帮我理解什么是错的(我已经花了两天时间)吗?
答案 0 :(得分:0)
我发现了这个错误。代码中有一个位置设置了viewmanager = null
。它按预期工作。