android 无法在viewpager中重新初始化片段时更新片段参数

muk1a3rh  于 2023-05-21  发布在  Android
关注(0)|答案(2)|浏览(172)

我正在调用Web服务时重新启动视图页导航中的片段,但无法更新片段中传递的参数。第一次通过的东西仍然是一样的。
验证码:

@Override
protected void onPostExecute(String response) {
 state = mOverviewData.getState();     
 setupViewPager(mViewPager, isSuccess);
}

private void setupViewPager(ViewPager viewPager, boolean isSuccess) 
{

        Adapter adapter = new Adapter(getSupportFragmentManager());
        if(isSuccess){
            fab.setVisibility(View.VISIBLE);
            Fragment chartFrag = new OverviewChartFrag();
            Bundle arg = new Bundle();
            arg.putString("state_name",  state);
            arg.putSerializable("total_blocks",  mOverviewData.getTotalBlock());
            arg.putSerializable("block_status_obj",  mOverviewData.getBlockStatusData());
            arg.putParcelableArrayList("mineral_wise_list", (ArrayList<? extends Parcelable>) mineralList);
            chartFrag.setArguments(arg);

            Fragment blocksFrag = new OverviewDataFrag();
            arg = new Bundle();
            arg.putString("state_name",  state);
            arg.putParcelableArrayList("public_data_list", (ArrayList<? extends Parcelable>) mOverviewData.getPublicTableData());
            blocksFrag.setArguments(arg);

            adapter.addFragment(chartFrag, getResources().getString(R.string.chart_tab));
            adapter.addFragment(blocksFrag, getResources().getString(R.string.data_tab));
            viewPager.setAdapter(adapter);
        } else {
            fab.setVisibility(View.GONE);
            Fragment noNetFrag = new ServerErrorFrag();
            adapter.addFragment(noNetFrag, getResources().getString(R.string.error));
            viewPager.setAdapter(adapter);
        }
    }
shstlldc

shstlldc1#

您不必在onPostExecute内部调用setupViewPager。使用下面的代码来获取以前添加的Fragment的引用并完成您的工作。

Adapter adapter = (Adapter) viewPager.getAdapter();
// we don't need but its a fail safe
if (adapter != null) {
    int childCount = adapter.getCount();
    for (int index = 0; index < childCount; index++) {
        Fragment fragment = (Fragment) adapter.instantiateItem(viewPager, index);
        // safe check
        if (fragment != null) {
            // you have a valid reference of your fragment, update its content or GUI
        }
    }
}

编码愉快。

nhhxz33t

nhhxz33t2#

你可以这样使用:

arguments?.let {
      synchronized(it) {
        arguments?.putString("YOUR_KEY", yourValue)
      }
    }

相关问题