如何将数据从活动传递到可滑动片段?
问题描述:
我有活动中的数据,我想在活动本身显示一些数据,以及一些我想在三个可滑动片段中显示的数据。那么我如何将数据从活动传递到该片段。我要把我想要做的事情形象化。 如何将数据从活动传递到可滑动片段?
请给解决这个问题。谢谢。
答
我认为你的主要问题是如何将数据从活动传递给片段?对吗?
您可以通过创建一个Bundle并将一些数据传递给它,然后将它传递给setArguments方法,从而将活动中的数据传递给fragment。
YourFragment yourFragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putInt(KEY_RECIPE_INDEX, index);//you can use bundle.putString or others to pass different types of data
yourFragment.setArguments(bundle);
现在,您可以通过使用getArguments
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int index = getArguments().getInt(ViewPagerFragment.KEY_RECIPE_INDEX);
//........
你也问你的问题,你有一些数据业务,且有些数据要显示在retrive在片段中的数据活动和其中一些你想要显示在swipble片段。现在我要告诉你如何通过使用一个例子来做到这一点。
假设你有两个滑动式标签,每个标签都有一个片段
final IngredientsFragment ingredientsFragment = new IngredientsFragment();
Bundle bundle = new Bundle();
bundle.putInt(KEY_RECIPE_INDEX, index);
ingredientsFragment.setArguments(bundle);
final DirectionsFragment directionsFragment = new DirectionsFragment();
bundle = new Bundle();
bundle.putInt(KEY_RECIPE_INDEX, index);
directionsFragment.setArguments(bundle);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewPager);
viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
@Override
public android.support.v4.app.Fragment getItem(int position) {
return position == 0 ? ingredientsFragment : directionsFragment;
}
@Override
public CharSequence getPageTitle(int position) {
return position == 0 ? "Ingredients" : "Directions";
}
@Override
public int getCount() {
return 2;
}
});
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
我觉得这是你想在你的活动,以显示数据的任何问题。
Qick回顾:通过创建一个bundle并放入一些数据并使用yourfragment.setArguments(yourBundle)将数据传递给fragment。
现在我认为你可以将数据传递给swipable视图。
希望这会有所帮助!
使用'bundle'发送数据 –
@Ravi发布代码您尝试使用的代码 – Gandhi