紧急:从viewpager更新1个片段,有两个片段

时间:2016-08-25 11:15:33

标签: android listview android-fragments android-viewpager

我在主要活动中有一个viewpager。在viewpager中,我有2个片段A和B.片段A有新闻主题的列表视图。当您点击listview上的每个项目时,新闻内容将显示在片段B上。 每当点击每个项目时,我的想法就是在listview适配器中设置setcurrentitem()。但我发现它不起作用。片段B不会在片段A的列表视图中显示来自第二个新闻的内容。这意味着viewpager不会更新片段B的内容

有人能告诉我如何解决这个问题吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以使用外部接口在活动和片段之间传递数据。你不应该直接在片段之间进行对话,使用Activity作为代理。示例如下:

MainActivity.java

public class MainActivity extends AppCompatActivity implements InteractionInterface {

    private ViewPager viewPager;

    private MyAdapter adapter;

    @Override
    public void onCreate(Bundle instance) {
        super.onCreate(instance);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        adapter = new MyAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
    }

    private class MyAdapter extends FragmentStatePagerAdapter {

        private FragmentA fragmentA;

        private FragmentB fragmentB;

        public MyAdapter(FragmentManager fm) {
            super(fm);
            fragmentA = new FragmentA();
            fragmentB = new FragmentB();
        }

        @Override
            public Fragment getItem(int position) {
            return position == 0 ? fragmentA : fragmentB;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }

    @Override
    public void onClick() {
        // this comes from InteractionInterface
        if(adapter.fragmentB.isAdded()) {
            adapter.fragmentB.doSomething("yeah!!");
        }
    }

}

FragmentA.java

public class FragmentA extends Fragment {

    private Button button;

    private InteractionInterface interface = null;

    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_a, container, false);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                if(interface != null) {
                    // you can modify this interface to pass some data
                    interface.onClick(); 
                }
            }
        });
        return rootView;
    }

    public void onAttach(Activity a) {
        super.onAttach(a);
        if (a instanceof InteractionInterface) {
            interface = (InteractionInterface) a;
        }
    }

    public void onDetach() {
        super.onDetach();
        interface = null;
    }

}

FragmentB.java

public class FragmentB extends Fragment {

    ...

    public void doSomething(String something) {
        // do stuff here
    }

}

InteractionInterface.java

public interface InteractionInterface {
    void onClick();
}