[英]Pass data from activity to another fragment
From the activity, I open the fragment "DevicesFragment" as below.在活动中,我打开如下片段“DevicesFragment”。 How do I transfer data from activity to fragment before starting it?如何在开始之前将数据从活动传输到片段? Thanks for help !感谢帮助 !
getSupportFragmentManager().beginTransaction().add(R.id.fragment, new DevicesFragment(), "devices").commit();
From Activity you send data with intent as:从 Activity 发送数据的目的是:
Bundle bundle = new Bundle();
bundle.putString("text", "From Activity");
// set Fragmentclass Arguments
DevicesFragment devices = new DevicesFragment();
devices.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.fragment, devices, "devices").commit();
and in DevicesFragment onCreateView method:在 DevicesFragment onCreateView 方法中:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle = getArguments();
if(bundle != null) {
String value = bundle.getString("text");
}
return inflater.inflate(R.layout.fragment, container, false);
}
You can send data from one activity to another fragment using Bundles as below:您可以使用 Bundles 将数据从一个活动发送到另一个片段,如下所示:
Bundle bundle = new Bundle();
bundle.putString("key", "your data");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and fragment onCreate method:和片段 onCreate 方法:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("key");
return inflater.inflate(R.layout.fragment, container, false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.