我正在使用片段构建计算器应用程序,我希望计算器片段在菜单项片段上按下后退按钮时显示。我一直在使用addToBackStac(null),但它对我不起作用。
以下是我的代码
公共类MainActivity扩展了ActionBarActivity {
FragmentManager fragmentManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
CalculatorFragment calc = new CalculatorFragment();
fragmentTransaction.add(R.id.relLejaut, calc);
fragmentTransaction.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.item) {
About about= new About();
// Insert the fragment by replacing any existing fragment
fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.relLejaut, about).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:0)
您需要首先在FragmentTransaction中添加()或替换()片段,然后调用addToBackStack()使其工作。
这样称呼:
fragmentManager.beginTransaction()代替(R.id.relLejaut,约).addToBackStack(空).commit();