猿问

编写 SharedPreferences 后更新布局?

我在这里的第一个线程 - 抱歉,如果文本格式不好。

我使用 Android Studio 3.1.3 API27 并为智能手机开发应用程序。

该应用程序目前由 1 个活动(分为 3 个片段)、第二个活动和 5 个 xml 文件组成。

通过使用 ViewPager,我可以浏览 3 个片段。

第二个片段(中间片段)包含 2 个按钮,每个按钮打开第二个活动,其中包含许多彩色按钮。

单击颜色按钮时,我可以更改第一个片段的背景颜色。

选择颜色后,第二个活动将关闭,我又回到活动 1 -> fragment2。

它有效,但问题是我总是必须刷到第 3 个片段,然后回到第 2 个片段,然后再刷到第 1 个片段。

如果我不这样做,片段 1 的颜色将保持旧颜色。

现在我正在寻找一种方法来更新片段 1 的布局,只要我按下活动 2 的颜色按钮。

我已经试过了:

  • 在编写 SharedPreferences (Activity2) 时,我使用 editor.apply() 而不是 editor.commit()

  • 读取 SharedPreferences (Activity1 -> Fragment1) 时,我使用 Context.MODE_MULTI_PROCESS 而不是 Context.MODE_PRIVATE

  • 使用 viewpage.setOffscreenPageLimit(0); 在我的 public void SetUpViewPager(ViewPager viewpage) 方法内的 MainActivity 中。

不过,没有任何帮助。

这是它的样子:

翻翻过去那场雪
浏览 157回答 3
3回答

慕斯王

您可以在 onResume() 方法中为每个片段更新 UI(或至少与颜色相关的部分),因此,当您从第二个活动返回时,它会刷新。

沧海一幻觉

使用事件总线在 Page_1 中注销和注册 EventBusonStop()和onStart() EventBus.getDefault().unregister(this) EventBus.getDefault().register(this)并使用它来发布值EventBus.getDefault().post(new MessageEvent("Change Color"));这个函数将处理 MessageEvent@Subscribe(threadMode = ThreadMode.MAIN)public void onMessageEvent(MessageEvent event) {    //change the color here    //add this function in Page_1 }当您更新颜色的值时。放入 MessageEvent文档

互换的青春

当一个 Fragment 可见时(即在你的 ViewPager 中被选中的页面),它的 setUserVisibleHint() 方法被调用。您可以在 Fragment 中覆盖该方法并使用它来触发刷新。 @Override    public void setUserVisibleHint(boolean isVisibleToUser) {        super.setUserVisibleHint(isVisibleToUser);        if(isVisibleToUser){         //you can check if the color is changed then refresh the fragment if not then don't do anything         //here you should refresh your fragment , this will called every time you         //view this fragment in all cases even if you didn't move to the          //third tab         }    }如何刷新片段    Fragment currentFragment = getFragmentManager().findFragmentByTag("YourFragmentTag");    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();    fragmentTransaction.detach(currentFragment);    fragmentTransaction.attach(currentFragment);    fragmentTransaction.commit();
随时随地看视频慕课网APP

相关分类

Java
我要回答