来自不同片段的 notifyDataSetChanged()

notifyDataSetChanged() from different fragment

我目前有 3 个片段(标签),目前正在使用 viewpager。我为每个片段有 1 个列表视图,我想在单击视图后发生某些事情时通知另一个。我尝试在 mainactivity 的 setOnPageChangeListener() 上使用 notifyDataSetChanged()。问题是,当我更改选项卡时,我可以看到正在插入的数据。由于更改发生在更改选项卡之后。

在您的 MainActivity 中。尝试使用此代码。可能会有帮助。

 @Override
    public void onPageSelected(int position) {
        // TODO Auto-generated method stub
        if (position ==0 )
            viewPager.getAdapter().notifyDataSetChanged();
        if (position == 1)
            viewPager.getAdapter().notifyDataSetChanged();
if (position == 2)
            viewPager.getAdapter().notifyDataSetChanged();
    }

您可以考虑使用广播接收器来通知数据集更改。

在你的接收片段中

public static final string RADIO_DATASET_CHANGED = "com.yourapp.app.RADIO_DATASET_CHANGED";

private Radio radio;

在onCreate方法中:

radio = new Radio();

接收片段中的无线电class:

private class Radio extends BroadcastReceiver{
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(RADIO_DATASET_CHANGED)){
                    //Notify dataset changed here
                }
        }

在 resume 方法的接收片段中:

@Override
        protected void onResume() {
            super.onResume();                    
                //using intent filter just in case you would like to listen for more transmissions
                IntentFilter filter = new IntentFilter();
                filter.addAction(RADIO_DATASET_CHANGED);                    
                getActivity().getApplicationContext().registerReceiver(radio, filter);
        }

确保我们在 onDestroy 方法中取消注册接收器

 @Override
protected void onDestroy() {
    super.onDestroy();

    try {
        getActivity().getApplicationContext().unregisterReceiver(radio);
    }catch (Exception e){
        //Cannot unregister receiver
    }

}

片段传输数据集已更改

然后从通知数据集更改的片段中执行:

Intent intent = new Intent(ReceivingFragment.RADIO_DATASET_CHANGED);
getActivity().getApplicationContext().sendBroadcast(intent);