我有一个简单的两屏应用程序。第一个屏幕向用户提供登录选项,第二个屏幕是他们在登录时看到内容的地方。
用户登录后,我将密钥设置为Flow.get( view ).set( Screens.CHAT )
.
一切都很好,但我遇到了一个问题,使我的视图看起来像这样:
当用户通过按主页按钮离开应用程序然后返回到它时(基本上是在 之后onRestart( )
),会发生这种视图的重新绘制。未填充RecyclerView
的将再次添加到视图层次结构中。
我的Dispatcher
逻辑是这样的:
public void dispatch(Traversal traversal, TraversalCallback callback) {
Object dest = traversal.destination.top();
Object source = traversal.origin == null ? null : traversal.origin.top();
ViewGroup root = (ViewGroup) activity.findViewById(R.id.root);
if (traversal.origin != null) {
int childCount = root.getChildCount();
// Our container has a root view with an ImageView in it.
// If child count > 1, we need to remove the child at position = 1
// because ImageView is at position = 0
if (childCount > 1) {
// save state
traversal.getState(traversal.origin.top()).save(root.getChildAt(1));
// remove the added views
removeAllViewsAfter(root,0);
}
}
@LayoutRes int layout;
if(dest.equals(Screens.WELCOME)){
layout = R.layout.view_welcome;
}else if(dest.equals(Screens.CHAT)){
layout = R.layout.view_chat;
}else{
throw new IllegalArgumentException("Unrecognized Screen");
}
View incomingView = LayoutInflater
.from(traversal.createContext(dest, activity))
.inflate(layout, root, false);
traversal.getState( traversal.destination.top() ).restore(incomingView);
root.addView( incomingView );
callback.onTraversalCompleted();
}
//----------------------------------------------------------------------------------------------
private void removeAllViewsAfter(ViewGroup root, int index){
for( int i = root.getChildCount() - 1; i > index; i-- ){
root.removeViewAt( i );
}
}
//----------------------------------------------------------------------------------------------
Dispatcher
为了避免相同的布局被夸大并再次添加,我应该在逻辑中进行哪些更改?