如何在MainActivity中调用onBackPressed,在android中扩展Fragment?

时间:2015-12-09 05:31:19

标签: android

我正在开发一个应用程序,其中MainActivity扩展了Fragment。这是我需要调用onBackPressed进行一些使用。我怎样才能实现这一目标?

我使用下面的代码无效

class MainActivity extends Freagment{
.
.
.
.

Override
public void onBackPressed() {
    super.onBackPressed();
}
}

上一页就像这样

class LoadWebData extends Activity
{
.
.
.
}

2 个答案:

答案 0 :(得分:0)

您可以通过调用addToBackStack方法将特定片段添加到Backstack。看看this示例。

MyDetailFragment myDetailFragment = new MyDetailFragment();
myDetailFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction =
getActivity().getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.phone_container, myDetailFragment);

/*
 * Add this transaction to the back stack. 
 * This means that the transaction will be remembered after it is 
 * committed, and will reverse its operation when later popped off 
 * the stack.
 */
fragmentTransaction.addToBackStack(null);

fragmentTransaction.commit();

答案 1 :(得分:0)

碎片不按后退听。我所看到的一个常见模式是在活动时与片段管理器进行交互,在触发背面时弹出片段....请参阅下面的代码!

@Override
public void onBackPressed() {

final FragmentManager fragmentManager = getFragmentManager(); 
final int count = fm.getBackStackEntryCount();

if (count == 0) {
    super.onBackPressed();
} else {
    fm.popBackStack();
}
}