一个片段里面FragmentTransaction
我使用jfeinstien10的 SlidingMenu
。在拔出菜单是一个片段
。当用户点击菜单项,但它确实是这样的:
I am using jfeinstien10's SlidingMenu
. The menu that pulls out is a Fragment
. When the user clicks on a menu item, it does something like this:
FragmentTransaction t = getActivity().getSupportFragmentManager().beginTransaction();
SherlockListFragment mFrag = new ItemsFragment();
t.replace(R.id.main_frag, mFrag);
t.commit();
不过,我听说这是不好的做法来控制片段
从另一个片段
。在这样的情况下,这是一个可以接受的方法是什么?或者,我应该用一个回调方法父 FragmentActivity
。
However, I have heard that it is not good practice to control a Fragment
from Another Fragment
. In a situation like this, is this an acceptable method? Or should I be using a Callback Method to the parent FragmentActivity
.
如果一个回调方法是适当的方式,我可以请参阅如何工作的例子吗?
If a Callback method is the proper way, can I please see an example of how this works?
相反的片段进行交易的,我建议你离开它的活动水平。要做到这一点,定义您的活动一个公共方法,然后从你的片段调用它。例如:
Instead of performing transaction in fragment, I would suggest you to leave it up to Activity level. To do that, define a public method in your activity and then call it from your fragment. For example:
假设你的活动是:
class MainActivity extends Activity{
....
public void replaceFragment(){
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
SherlockListFragment mFrag = new ItemsFragment();
t.replace(R.id.main_frag, mFrag);
t.commit();
}
....
}
和您的片段中,进行下面的调用:
And within your fragment, make the following call:
((MainActivity)getActivity()).replaceFragment();