0

我已经下载了一个示例应用程序,上面有两个片段。左侧片段显示项目,右侧片段显示基于选择的项目的联系。

我想要做的是在左侧片段上还有一个按钮,可用于更新显示的列表。因此,为什么我想要一个列表和一个按钮同时出现在同一个片段上。

这可以做到吗。我的示例代码是: -

布局xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment android:name="com.example.android.fragments.HeadlinesFragment"
              android:id="@+id/headlines_fragment"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="match_parent" />

    <fragment android:name="com.example.android.fragments.ArticleFragment"
              android:id="@+id/article_fragment"
              android:layout_weight="2"
              android:layout_width="0dp"
              android:layout_height="match_parent" />

</LinearLayout>

主要活动代码是: -

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first
    // fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment firstFragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from
        // an Intent,
        // pass the Intent's extras to the fragment as arguments
        firstFragment.setArguments(getIntent().getExtras());

        FragmentManager fragmentManager = getFragmentManager();

        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();

        transaction.add(R.id.fragment_container, firstFragment);

        transaction.commit();

    }
}

R.id.fragment_container 完成后是否还可以出现一个按钮。

谢谢

马丁

4

1 回答 1

0

有很多方法可以做到这一点。最简单的方法是让activity保持对fragment的引用,并在listfragment中创建一个方法,该方法可以通过activity中的方法被其他fragment调用。

另一种方法是通过广播。

第三种方法是使用 RoboGuice 并在两个片段中注入一个类,以建立片段之间的通信。

于 2012-11-01T11:42:08.060 回答