我有一个 MainActivity
,它包含一个带有两个 fragment 的标签栏:MainFragment
和 WishlistFragment
。它们都扩展为 ListFragment
。
当有人触摸“选项”菜单中的菜单项时,我希望正在显示 的 fragment 中的 ListView 使用名为 LazyAdapter 适配器
的自定义适配器刷新其列表。
所以这里是我希望在我的 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;
}
}
我该怎么做?我不确定如何调用 fragment 以及如何确定显示的是哪个 fragment。
下面是我在 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?
第 1 步:修复 onTabSelected()
的实现。您不希望每次用户选择选项卡时都创建一个新 fragment 。相反,您希望有两个 fragment ,由数据成员中的 Activity 保留,并在 replace()
事务中使用它们。
第 2 步:需要时,调用 ActionBar
上的 getSelectedNavigationIndex()
,使用它来选择您需要的两个 fragment 中的哪一个(从提到的数据成员中获取)在上面的步骤 #1 中),并在 fragment 上调用一些方法来执行您想要的操作。
关于java - 如何从主 Activity 刷新 Fragment 中的 ListView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13203088/