如何将数据从片段传递到Tablayout片段

时间:2019-12-22 15:59:29

标签: java android-studio

这将在使用viewpageAdapter的片段中运行片段。我想将数据从片段传递到tablayout片段。我尝试了任何方法,仍然崩溃。我只想传递一次数据以在TabLayout中分段。

第一个片段。这行我想传递给tablayout片段:-

specItem = getArguments().getString("spec_item");

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

    imageUrl = getArguments().getString("image_url");
    priceItem = getArguments().getString("price_item");
    specItem = getArguments().getString("spec_item");

}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_view_details_item, container, false);

    textPrice = (TextView) rootView.findViewById(R.id.textPrice);
    image_Details = (ImageView) rootView.findViewById(R.id.image_Detail);
    tabLayout = (TabLayout) rootView.findViewById(R.id.tablayout_id);
    viewPager = (ViewPager) rootView.findViewById(R.id.viewpage_id);

    textPrice.setText(priceItem);

    Picasso.get().load(imageUrl).into(image_Details);

    ViewPageAdapter adapter = new ViewPageAdapter(getActivity().getSupportFragmentManager());
    adapter.AddFragment(new FragmentSpecifications(), "Specification");
    adapter.AddFragment(new FragmentReview(), "Review");

    viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);


    return rootView;
}

tablayout中的第二个片段,我不知道该如何接收:-

View rootView;

TextView textSpec;
String specItem;
public FragmentSpecifications() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_specification, container, false);

    textSpec = (TextView) rootView.findViewById(R.id.textviewspec);

    textSpec.setText();

    return rootView;
}

1 个答案:

答案 0 :(得分:0)

在您的FragmentSpecifications内创建Fragment的实例,以向其发送数据,如下所示:

public static FragmentSpecifications newInstance(String priceItem) {

    Bundle args = new Bundle();
    args.putString("priceItem", priceItem);
    FragmentSpecifications fragment = new FragmentSpecifications();
    fragment.setArguments(args);
    return fragment;
}

之后,以相同的FragmentSpecifications覆盖onCreate方法并获取值:

private String priceItem;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null)
       priceItem = getArguments().getString("priceItem");
}

最后,当您添加FragmentSpecifications时,请适配器传递值:

adapter.AddFragment(FragmentSpecifications.newInstance(priceItem), "Specification");