【问题标题】:Refreshing fragments on filter selection from parent activity从父活动中刷新筛选器选择的片段
【发布时间】:2017-05-18 19:31:22
【问题描述】:

我有这种情况,我有一个 Activity(A),它有 2 个选项卡(即两个片段 FA1,FA2)。 Activity A 中的 appBar 有一个过滤器按钮,可根据选择的选项卡打开不同的 Activity(B & C)。 这已由 A 中的以下代码处理。

  toolbar.findViewById(R.id.filterimage).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = null;
            if (tabLayout.getSelectedTabPosition() == 1) {
                i = new Intent(A.this, B.class);

            } else {
                i = new Intent(A.this, C.class);
            }
            startActivityForResult(i, 221);

        }
    });

在两个片段中显示数据的所有 api 命中都是在各自的片段中进行的。从活动 B 或 C 中选择的过滤器返回到活动 A 。 现在根据选择的过滤器,我想再次从它的父活动刷新片段(FA1 或 FA2),即。一个。 但我无法这样做。 我怎样才能做到这一点?

【问题讨论】:

  • 可以刷新片段。您可以在活动中获得这些片段的链接,然后致电fragment1.doSomething()
  • @rajat44 我猜你可以在 onResume() 上刷新片段,如果你还没有尝试过的话!!
  • 如果我这样做 Fragment fragment = new Fragment(); ?或 TabLayout.Tab tab = tabLayout.getTabAt(1); tab.select();
  • 选择过滤器后返回Activity A时是否要刷新fragments?

标签: android android-fragments android-activity


【解决方案1】:
@Override
protected void onResume() {
    super.onResume();

 // Where currentFragment is the fragment you want to refresh

 getSupportFragmentManager()
.beginTransaction()
.detach(currentFragment)
.commitNowAllowingStateLoss();

 getSupportFragmentManager()
.beginTransaction()
.attach(currentFragment)
.commitAllowingStateLoss();

 }

这里你必须检查来自 B 或 C 活动的特定情况,否则不要刷新。

【讨论】:

  • 成功了!!但是上面的代码是做什么的?你能解释一下代码吗?谢谢!!
  • @rajat44 很高兴听到这个消息,正如名称所示,我们使用前 4 行来分离您的片段,然后它就像第一次加载一样附加。对于 commitAllowingStateLoss,请查看this 了解更多信息
【解决方案2】:

对两者使用不同的请求代码,如下所示:

toolbar.findViewById(R.id.filterimage).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent i = null;
        if (tabLayout.getSelectedTabPosition() == 1) {
            i = new Intent(A.this, B.class);
            startActivityForResult(i, 221);

        } else {
            i = new Intent(A.this, C.class);
            startActivityForResult(i, 222);
        }

    }
});

然后依赖请求代码获取结果并更新片段数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多