我知道这个问题已被提出,但我没有成功回答。
我有一个带有回收站视图的片段。我有一个按钮,可以显示和隐藏这个片段。这一切都很好,直到屏幕的变化。然后重新创建片段,顶部的片段显示并隐藏,但后面有一个片段留在那里。
我知道我需要使用
if (savedInstanceState == null)
在某个地方,但无法成功在哪里。非常感谢,
这是我的代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
recyclerViewFragment = new RecyclerViewFragment();
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.add(R.id.recycle_view_container, recyclerViewFragment, RECYCLER_FRAGMENT);
trans.commit();
trans.show(recyclerViewFragment);
Button showHideButton = (Button)findViewById(R.id.button_show_hide);
showHideButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showHideFragment(recyclerViewFragment);
}
});
showHideButton.playSoundEffect(SoundEffectConstants.CLICK);
}
public void showHideFragment(final Fragment fragment){
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.setCustomAnimations(android.R.anim.slide_in_left , android.R.anim.slide_out_right);
if (fragment.isHidden()) {
trans.show(fragment);
Log.d("hidden","Show");
} else {
trans.hide(fragment);
Log.d("Shown","Hide");
}
trans.commit();
}
非常感谢大家!!!!!!!
答案 0 :(得分:1)
而不是:
trans.add(R.id.recycle_view_container, recyclerViewFragment, RECYCLER_FRAGMENT);
试试这个:
trans.replace(R.id.recycle_view_container, recyclerViewFragment, RECYCLER_FRAGMENT);
该名称具有误导性。如果是第一次,Replace
实际上也可以作为添加。发生的事情是,当您的活动轮换时,再次调用onCreate()
,以便您在现有活动的基础上添加相同的片段
答案 1 :(得分:1)
我建议您对代码进行一些更改 我想RECYCLER_FRAGMENT是一个常量,包含用于标记片段的标记
RecyclerViewFragment recyclerViewFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if(savedInstanceState == null) {
recyclerViewFragment = new RecyclerViewFragment();
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.add(R.id.recycle_view_container, recyclerViewFragment, RECYCLER_FRAGMENT);
trans.commit();
}else{
recyclerViewFragment = getSupportFragmentManager().findFragmentByTag(RECYCLER_FRAGMENT);
if(savedInstanceState.getString("vi").equals("hid")){
getSupportFragmentManager().beginTransaction().hide(recyclerViewFragment).commit();
}
}
Button showHideButton = (Button)findViewById(R.id.button_show_hide);
showHideButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager manager = getSupportFragmentManager();
if (fragment.isVisible()) {
manager.beginTransaction().hide(recyclerViewFragment).commit();
} else {
manager.beginTransaction().show(recyclerViewFragment).commit();
}
}
});
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(recyclerViewFragment.isVisible() == true){
outState.putString("vi","vis");
}else{
outState.putString("vi", "hid");
}
}