您将采用<代码>Fragment Transaction,并使用replace(
)方法。
这样做太困难,但答案取决于您的所在地。 Menu(即:onOptionsItemS(<>/code>)在您的母体内打电话。 活动或活动是否在A/B节中?
为了简单起见,您的菜单执行和onOptionsItemS(
)的证明属于母体活动,如果选择菜单,你想要重塑碎块。 它想看一下:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
//...
switch (item.getItemId()) {
case R.id.menu_option1:
//do something
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new YourFragmentClass();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.your_fragment_id, newFragment);
transaction.addToBackStack(null);
transaction.commit();
return true;
case R.id.menu_option2:
//do something else;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Alternatively, if your menu is a child of one of your Fragments (which it should be for the sake of more reusable code), then one method is to require that host Activity to implement an interface defined by the Fragment, that can be used as a call back.
And in the onOptionsItemSelected()
callback inside your fragment class, you simply make a call to this callback method.
尽管它像一个口号一样健全,但你确实需要做两件事。 认为这是你的分裂阶层
public static class FragmentA extends ListFragment {
OnSelectedListener mListener;
// Container Activity must implement this interface
public interface OnSelectedListener {
public void onSelected();
}
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//This is to ensure that the Activity has implemented the interface we set up above
try {
mListener = (OnSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnSelectedListener");
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
//...
switch (item.getItemId()) {
case R.id.menu_option1:
//do something
getActivity().onSelected();
return true;
case R.id.menu_option2:
//do something else;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
...
}
然后,你们会看到:
public class MainActivity extends Activity implements FragmentA.onSelectedListener{
...
public void onSelected(){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new YourFragmentClass();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.your_fragment_id, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}