如何将相同的值从主活动传递到所有片段Trough视图分页器

时间:2017-10-02 20:15:22

标签: android android-fragments

我使用viewpager创建了这个带有片段的滑动标签但是我需要传递一些数据让我们说来自父活动的所有片段的id如何实现这一点请帮助

主要活动。这里创建滑动标签活动并加载片段 -

public class SimpleTabsActivity extends AppCompatActivity {

private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_tabs);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), "Category-1");
    adapter.addFragment(new TwoFragment(), "Category-2");
    adapter.addFragment(new ThreeFragment(), "Category-3");
    viewPager.setAdapter(adapter);
    viewPager.setOffscreenPageLimit(2);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }



    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

}
}

示例片段代码 -

 public class OneFragment extends Fragment{


public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_one, container, false);
}

}

0 个答案:

没有答案