【问题标题】:Start a ListFragment from Activity从 Activity 启动 ListFragment
【发布时间】:2015-07-23 01:18:24
【问题描述】:

我正在开发一个应用程序来呈现地图(使用片段)和列表(使用 ListFragment)。因此,根据用户的偏好,我有一个启动应用程序以及 mapfragment 或列表片段的活动。我可以用 FragmentManager 和 FragmentTransaction 轻松替换 mapfragment 的当前活动。我遇到的问题是如何从活动中调用或启动 ListFragment。 listfragment 使用 ListViewAdapter 类来扩展自定义布局(重复使用不同的信息),因此如果我想使用事务,则有必要在布局中使用 listview 容器。问题是我使用的是项目布局而不是容器。

有什么想法可以解决这个问题或任何其他方式来处理在活动中开始呈现列表片段?

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    如果您尝试同时显示两个不同的片段,请查看此documentation,但基本思想是在您的活动布局中包含多个FrameLayouts。也不要忘记View.setVisibility()

    ListFragments 的启动方式与任何其他 Fragment 相同。

    例如:

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_frame, new MyListFragment()
                    .commit();
    

    一个更详细的例子:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.plusButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.content_frame, new MyListFragment())
                        .commit();
            }
        });
    
    }
    

    activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:tools="http://schemas.android.com/tools"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:paddingLeft="@dimen/activity_horizontal_margin"
                    android:paddingRight="@dimen/activity_horizontal_margin"
                    android:paddingTop="@dimen/activity_vertical_margin"
                    android:paddingBottom="@dimen/activity_vertical_margin"
                    tools:context=".MainActivity">
    
    
        <FrameLayout
            android:id="@+id/content_frame"
            android:clickable="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:text="Press For List"
            android:id="@+id/plusButton"
            android:layout_gravity="center"/>
    </RelativeLayout>
    

    【讨论】:

    • 非常感谢您的解释和示例。我遵循了您的回答,现在我的应用程序运行良好。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多