简体   繁体   English

更新Android中的片段

[英]Update fragment in android

say I have a few fragments displaying and doing certain things. 说我有一些片段显示和做某些事情。 Now, based on some event, I want to change the screen(or content) for a fragment. 现在,基于某个事件,我想更改片段的屏幕(或内容)。 [EDIT] [编辑]

For example. 例如。

My first layout, layout A, has a listview. 我的第一个布局A是一个listview。 And another layout, layout B has a table view. 另一个布局B拥有一个表格视图。 I am currently displaying the layout A in the fragment. 我目前正在片段中显示布局A。 On list item click, I want to display layout B in the same fragment. 单击列表项时,我要在同一片段中显示布局B。

How is this done? 怎么做?

Thanks. 谢谢。

If I understand your question correctly this is how I would go about it. 如果我正确理解了您的问题,那么我将如何处理。

I assume you have created fragment classes for your list fragment (fragment A) and view fragment (fragment B). 我假设您已经为列表片段(片段A)和视图片段(片段B)创建了片段类。

We can use the fragmentManager to be able to swap out fragments in the layout view. 我们可以使用fragmentManager来交换布局视图中的片段。

//grab fragmentManager, this will allow us to switch out fragments
FragmentManager fragManager = getFragmentManager();
FragmentTransaction fragTransaction = fragManager.beginTransaction();

//first remove the current fragment
fragTransaction.remove(fragManager.findFragmentById(R.id.layout_view));

//replace the current FragmentA with FragmentB
fragTransaction.replace(R.id.layout_view, new FragmentB());

//add to backstack if you want the android back button to work properly
fragTransaction.addToBackStack(null);

//and lastly, we commit the changes to the fragmentManger's transaction
fragTransaction.commit();

Hopefully this helps. 希望这会有所帮助。

My first layout, layout A, has a listview. 我的第一个布局A是一个listview。 And another layout, layout B has a table view. 另一个布局B拥有一个表格视图。 I am currently displaying the layout A in the fragment. 我目前正在片段中显示布局A。 On list item click, I want to display layout B in the same fragment. 单击列表项时,我要在同一片段中显示布局B。

How is this done? 怎么做?

You could use the new nested fragments API(available through the compatibility package and with normal fragments API 16+). 您可以使用新的嵌套片段API(可通过兼容性软件包获得,并与常规片段API 16+一起使用)。 Instead of the current Fragment that holds a ListView (and which you'll replace by a table), you'll have a wrapper Fragment , one that has as its view a single FrameLayout for its content. 您将拥有一个包装器Fragment ,而不是拥有一个ListView的当前Fragment (您将用一个表替换它),该包装器的视图具有单个FrameLayout作为其内容。

You'll then create two fragments one containing the ListView and containing the table layout. 然后,您将创建两个片段,一个片段包含ListView和表格布局。 Initially you'll add the list based fragment to the wrapper fragment to obtain the start layout and on the item click event you'll use the getChildFragmentManager() to replace the list based fragment with the table based fragment(all in the wrapper fragment). 最初,您将基于列表的片段添加到包装器片段中以获取开始布局,并在项目单击事件中,将使用getChildFragmentManager()将基于列表的片段替换为基于表的片段(所有在包装器片段中) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM