あなたのアプローチはうまく機能する可能性がありますが、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>