[英]How can I refresh a ListView in a Fragment from the main Activity?
I have a MainActivity
which contains a tab bar with two fragments: MainFragment
and WishlistFragment
. 我有一个MainActivity
,它包含一个带有两个片段的标签栏: MainFragment
和WishlistFragment
。 They both extend as ListFragment
. 它们都扩展为ListFragment
。
When someone touches a menu item from the Option menu, I want the ListView within the Fragment that is showing to refresh its list using its custom adapter called LazyAdapter adapter
. 当有人触摸选项菜单中的菜单项时,我希望显示的片段中的ListView使用名为LazyAdapter adapter
自定义适配器刷新其列表。
So in here is where I want the refresh to go in my MainActivity
code: 所以在这里我希望刷新进入我的MainActivity
代码:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_edit:
// find out which fragment is showing here
// refresh the fragment's listview here
// adapter.notifyDataSetChanged();
return true;
}
}
How can I do this? 我怎样才能做到这一点? I am not sure how to call forward into the fragment and how to determine which fragment is showing. 我不知道如何调用片段以及如何确定显示哪个片段。
Here is how I have my tabs set up in MainActivity
: 以下是我在MainActivity
设置标签的方法:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar.addTab(actionBar.newTab().setText("Main").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Wishlist").setTabListener(this));
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the container
ListFragment newfragment = null;
switch (tab.getPosition() + 1)
{
case 1:
newfragment = new MainFragment();
break;
case 2:
newfragment = new WishlistFragment();
break;
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, newfragment)
.commit();
}
How can I do this? 我怎样才能做到这一点?
Step #1: Fix your implementation of onTabSelected()
. 步骤1:修复onTabSelected()
。 You do not want to be creating a new fragment each time the user chooses a tab. 每次用户选择选项卡时,您都不希望创建新片段。 Instead, you want to have two fragments, held onto by the activity in data members, and use those in the replace()
transaction. 相反,您希望有两个片段,由数据成员中的活动保留,并在replace()
事务中使用它们。
Step #2: When needed, call getSelectedNavigationIndex()
on the ActionBar
, use that to choose which of the two fragments you need (obtained from the data members mentioned in Step #1 above), and call some method on the fragment to do what you want. 步骤#2:需要时,在ActionBar
上调用getSelectedNavigationIndex()
,用它来选择你需要的两个片段中的哪一个(从上面步骤1中提到的数据成员中获得),并调用片段上的一些方法来做什么你要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.