java - 如何从主 Activity 刷新 Fragment 中的 ListView?

标签 java android eclipse android-listview android-fragments

我有一个 MainActivity,它包含一个带有两个 fragment 的标签栏:MainFragmentWishlistFragment。它们都扩展为 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/

相关文章:

java - 使用 Apache Camel 调用 Docker 容器中的服务时响应时间较长

java - 是什么导致了 API 级别的变化?

java - 使用 Picasso 和 RecyclerAdapter 在 Activity 之间传递图像

java - 从插件写入 'Problems' 表或 'Console'

eclipse - 如何配置 git 服务器来共享项目

java - 使用java创建对象CoreNLP

java - 将不规则二维数组中的子数组设为 Null

java - @Qualifier 无法帮助我解决 beans 歧义问题

android - 我如何将文件复制到 android 上的/data/data/... 目录?

java - 在JRE 8中使用printf