每次打开片段时,它都会被添加到堆栈中。 所以,后退按钮会根据堆栈返回给我。
我想每次打开片段时都要删除堆栈。
如果是的话,我怎么能这样做? 这是我的代码public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
FragmentTransaction transaction;
LinearLayout firstColumn,secondColumn,thirdColumn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
firstColumn = (LinearLayout) findViewById(R.id.first_column);
secondColumn = (LinearLayout) findViewById(R.id.second_column);
firstColumn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.main_container_frame_layout, new FirstFragment());
transaction.commit();
}
});
secondColumn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.main_container_frame_layout, new SecondFragment());
transaction.commit();
}
});
}
}
提前谢谢。
答案 0 :(得分:0)
getSupportFragmentManager()。popBackStack()将根据堆栈返回。下面的代码可以帮到你。
@Override
public void onBackPressed() {
if(getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
}else
super.onBackPressed();
}