【问题标题】:How to refresh listview in a tab from another activity?如何从另一个活动刷新选项卡中的列表视图?
【发布时间】:2017-09-11 03:12:10
【问题描述】:

我有一个选项卡式活动,其中一个选项卡有最喜欢的电影 recyclerView 列表。在另一个选项卡中,将显示所有电影,单击一部电影将打开电影详细信息活动,他可以在其中收藏该电影。我只在共享偏好中保存最喜欢的电影的 ID。在他回到最喜欢的选项卡后,我可以获取所有电影并显示它,但是对于每一个新电影添加,获取所有最喜欢的项目并不是一个好主意,并为新喜欢的电影维护静态变量并刷新列表看起来不是个好主意。

我正在考虑为此使用接口、广播接收器或 RxJava 方法。但是对于界面,我不能一直在电影详情活动中持有最喜欢的选项卡实例。 Rxjava 的 Publish 主题也不错,但我需要维护静态引用以从电影详细信息活动中发送事件。

我认为广播接收器或 Rxjava 方法是最好的方法。请帮助我选择正确的实现。

【问题讨论】:

标签: android listview android-recyclerview rx-android rx-java2


【解决方案1】:

您可以在下一个片段中获得响应后从上一个片段中广播意图确保仅加载下一个片段/选项卡您还可以在 Activity 中设置数据,因此如果对数据片段所做的任何更改都可以合并它并且不要覆盖destroyItem这将 再次帮助重新创建 fagment 对象,您将获得新的数据...当

您必须从下一个片段到上一个片段进行更改!

@Override
protected void onPostExecute(Object o) {
    super.onPostExecute(o);
    Intent intent = new Intent("key_to_identify_the_broadcast");
    Bundle bundle = new Bundle();
    bundle.putString("edttext", json.toString());
    intent.putExtra("bundle_key_for_intent", bundle);
    context.sendBroadcast(intent);
}

然后您可以使用 BroadcastReceiver 类在片段中接收捆绑包

private final BroadcastReceiver mHandleMessageReceiver = new 
BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = 
            intent.getExtras().getBundle("bundle_key_for_intent");
            if(bundle!=null){
                String edttext = bundle.getString("edttext");
            }
            //you can call any of your methods for using this bundle for your use case
    }
};

在你的片段的 onCreateView() 中,你需要先注册广播接收器,否则这个广播接收器将不会被触发

IntentFilter filter = new IntentFilter("key_to_identify_the_broadcast");
getActivity().getApplicationContext().
               registerReceiver(mHandleMessageReceiver, filter);

最后你可以取消注册接收器以避免任何异常

@Override
public void onDestroy() {
    try {

         getActivity().getApplicationContext().
             unregisterReceiver(mHandleMessageReceiver);

    } catch (Exception e) {
        Log.e("UnRegister Error", "> " + e.getMessage());
    }
    super.onDestroy();
}

您可以在所有片段中创建单独的广播接收器,并使用相同的广播将数据广播到所有片段。您还可以对不同的片段使用不同的密钥,然后对特定的片段使用特定的密钥进行广播。

【讨论】:

    【解决方案2】:

    在你的情况下,你需要指定setOffscreenPageLimit 0,这样当你在第二页时,第一页被销毁,反之亦然。

    所以,每次你点击 listViewrecylerView 时再次加载。

    mViewPager = (ViewPager)findViewById(R.id.pager);
    mViewPager.setOffscreenPageLimit(0);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      相关资源
      最近更新 更多