繁体   English   中英

如何将数据从 Fragment 传递到 Tablayout Fragment

[英]How to pass data from Fragment to Tablayout fragment

这将在使用 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;
}

你里面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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM