我要处理片段
中的onBackPressed
我在活动中使用以下代码,但返回0
@Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
Toast.makeText(getBaseContext(), ""+count, Toast.LENGTH_SHORT).show();
if (count == 1) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
答案 0 :(得分:0)
只需在您的.addToBackStack(null)
或Activity
中添加Fragment
即可。添加或替换fragment
时。像下面一样
getSupportFragmentManager().beginTransaction().replace(R.id.parent_layout, new MyFragment()).addToBackStack(null).commit();
注意:-您无需在onBackPressed()
方法中做任何事情。
答案 1 :(得分:0)
Just app this line when you want to replace any fragment and manage backsack on Fragment.
ClientHome per = new ClientHome();
Bundle bundle = new Bundle();
bundle.putString("usertype", "client");
per.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_from_left, R.anim.slide_to_right);
fragmentTransaction.replace(R.id.content_frame, per, "tag");
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();