从MainActivity“刷新”片段

时间:2012-08-15 19:00:48

标签: android android-fragments android-listfragment

因此,ListFragment中有一个按钮。按钮的onCLick方法在MainActivity中实现(不确定它是否是正确的解决方案,但它是什么)。当我单击按钮时弹出AlertDialog,当我选择其中一个对话框选项时,它会更改我的片段正在使用的数据集。

问题是当AlertDialog消失时,我的ListFragment仍在显示旧数据。

有没有办法从ListFragment更新我的MainActivity

我已尝试将某些ListFragment方法设为静态,以便可以从主活动中调用它们,但这些方法使用非静态字段等,因此不能是静态的。

4 个答案:

答案 0 :(得分:1)

您应该能够通过在其适配器上调用notifyDataSetChanged()来更新ListFragments(假设您的适配器派生自BaseAdapter或其任何子类)。最简单的方法可能是在对话框中设置DialogInterface.OnDismissListener

myDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
  @Override
  public void onDismiss(DialogInterface dialog){
    myBaseAdapter.notifyDataSetChanged();
  }
});

您可以保留对适配器的引用,也可以直接从ListFragment获取,具体取决于您的实现。

答案 1 :(得分:1)

所以,我将我的ListFragment片段的适配器声明为静态,以及我声明了一个从中填充此适配器的列表 - 作为静态。

从主要活动我这样做:

ListFragment.item.add(mChosenFilePath);
ListFragment.fileList.notifyDataSetChanged();

其中:

item - 是一个包含要显示的元素的列表

mChosenFilePath - 作为对话结果添加到item的文件路径

fileList - 是我的适配器

答案 2 :(得分:0)

有三种可能的解决方案。

  1. 听取片段中的点击而不是“活动”。
  2. 在对话框的cancel按钮上设置一个监听器,并根据需要重新加载该片段。
  3. 使用标记添加片段,通过该标记从管理器获取,并调用相应的方法。

答案 3 :(得分:0)

为片段设置标记或ID。然后,您可以直接在Activity:

上的片段上调用方法
Fragment myne = findFragmentByTag( "MyFragment" );
MyFragment target = (MyFragment) myne;
target.refresh(); // 'Refresh' method to be declared by MyFragment implementation