您的方法可能工作正常,但最好使用更松散耦合的方法,其中 ListFragment 通知宿主活动已单击项目,然后活动通知“其他”片段进行更新。
无需担心构建和替换新片段。
示例活动
public class TestActivity extends Activity implements TestFragmentBListener {
private TestFragmentA mOtherFragment;
private TestFragmentB mListFrag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mListFrag = (TestFragmentB) getFragmentManager().findFragmentById(R.id.fragment_b_list);
mOtherFragment = (TestFragmentA) getFragmentManager().findFragmentById(R.id.fragment_a_text);
}
@Override
public void onTestFragmentBItemCLicked(int position) {
// Implemented from TestFragmentB.TestFragmentBListener
mOtherFragment.setText("item " + position + " selected.");
}
}
示例 FragmentA(包含文本.. 这不起作用,仅作为示例)
public class TestFragmentA extends Fragment {
public void setText(String text) {
}
}
示例 ListFragment 定义了示例活动要实现的接口
public class TestFragmentB extends ListFragment {
private TestFragmentBListener mListener = null;
public interface TestFragmentBListener {
void onTestFragmentBItemCLicked(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (TestFragmentBListener) activity;
} catch (ClassCastException ccex) {
// activity does not implement our listener
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (mListener != null) {
mListener.onTestFragmentBItemCLicked(position);
}
}
}
为了完整起见,这是我对示例活动的布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestActivity" >
<fragment
android:id="@+id/fragment_a_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<fragment
android:id="@+id/fragment_b_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/fragment_a_text" />
</RelativeLayout>