一切!
我有2个片段。第一个出现在开始,第二个用按钮添加"添加",使用相同的容器。我正在尝试使用方法addToBackStack
将片段添加到后台堆栈,但是当我点击&#34时;后退按钮"我的应用程序隐藏而不是向我显示第一个片段。怎么了?
public class MainActivity extends AppCompatActivity {
FirstFragment fragment1;
SecondFragment fragment2;
FragmentTransaction fragmentTransaction;
FragmentManager fm;
Button add;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fragment1 = new FirstFragment();
fragment2 = new SecondFragment();
add = (Button) findViewById(R.id.add);
fm = getFragmentManager();
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.add(R.id.container, new FirstFragment());
fragmentTransaction.commit();
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, new SecondFragment());
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
答案 0 :(得分:0)
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}