Android:Single Fragment在同一个表格中显示列表和按钮

时间:2012-11-01 11:08:12

标签: android fragment

我已下载了一个示例应用,其上有两个片段。左侧片段显示项目,右侧片段根据选择的项目显示相应的内容。

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

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

layout 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完成后,是否还可以显示一个按钮。

由于

马丁

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。最简单的方法是让活动保持对片段的引用,并在列表片段中创建一个方法,该方法可以由另一个片段通过活动中的方法调用。

另一种做法是通过广播。

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