我有Activity1将我带到了Activity2,这将我带到了片段。我想从碎片到返回活动2
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else
super.onBackPressed();
}
添加activity的片段2
将其添加到背面getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_layout, new SampleFragment())
.addToBackStack(SampleFragment.class.getSimpleName())
.commit();
和onbackpressed检查片段是否存在于背串中并弹出
@Override
public void onBackPressed() {
if(getSupportFragmentManager().getBackStackEntryCount()>0){
Fragment fragment=getSupportFragmentManager().findFragmentById(R.id.YOUR_FRAME_LAYOUT_ID);
if(fragment!=null && fragment.getClass().getSimpleName().equalsIgnoreCase(SampleFragment.class.getSimpleName())){
getSupportFragmentManager().popBackStackImmediate();
}
}else {
super.onBackPressed();
}
}
在片段上获取后压事件,并在那里调用
getactivity().getsupportfragmentmanager().popbackstack();
将片段交易添加到背面。