一个片段与另一个片段之间的通信
我是新来的片段。我在第一个片段中添加了两个编辑文本,我想将该编辑文本数据发送到第二个片段。一个片段与另一个片段之间的通信
我正在使用一个包,但它在第二个片段中打印null。
谁能告诉我如何发送数据到其他片段?
第一个片段
nextt.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View _view) {
int viewId = _view.getId();
FragmentTransaction ft;
switch (viewId) {
case R.id.Button1:
FragmentManager fm = getFragmentManager();
ft = fm.beginTransaction();
SecondFrag secondFrag = new SecondFrag();
Bundle bundle = new Bundle();
bundle.putInt("deviceInst",viewId);
secondFrag.setArguments(bundle);
ft.replace(R.id.total_frame_content, secondFrag);
ft.addToBackStack(null);
ft.commit();
break;
}
}
});
在第二个片段
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_new, container, false);
String value = getArguments().getString("deviceInst");
System.out.println("TTTT"+ value);
在你的第一个片段中,你传递一个int
作为参数。
bundle.putInt("deviceInst",viewId);
,然后在你的第二个片段您尝试使用 getArguments().getString("deviceInst")
这将无法得到这样的说法,所以让你通过,你需要使用getArguments().getInt("deviceInst")
参数为了封装所需的数据,一个好的提示是在需要数据的片段中有一个静态的newInstance()
方法。
这是关于它的一篇文章。
https://plus.google.com/+AndroidDevelopers/posts/bCD7Zvd945d
您需要更改像
int value = getArguments().getInt("deviceInst");
,而不是
String value = getArguments().getString("deviceInst");
你需要在你的代码以下更改。
bundle.putString("deviceInst",editText.getText().toString());
然后在你的第二个片段则可以通过使用
getArguments().getString("deviceInst")
这里EDITTEXT是在第一个片段编辑文本的情况下获得这样的说法。
Bro如何传递listview数据? – pruthvi
listView。setOnItemClickListener(),然后onItemClick从您提供的数组列表/数据源中检索数据。 –
As you have passed int in the bundle, you need to use getInt() in your receiver fragment.
For example:
SecondFrag secondFrag = new SecondFrag();
Bundle bundle = new Bundle();
bundle.putInt("deviceInst",viewId);
secondFrag.setArguments(bundle);
getFragmentManager().beginTransaction().add(R.id.total_frame_content, secondFrag).commit();
In receiver fragment
String value = getArguments().getInt("deviceInst");
一定要仔细阅读本https://developer.android.com/training/basics/fragments/communicating.html – Raghunandan
你路过诠释和获得在字符串检查你的代码 –
@Ashwini Bhat..if我想在这种情况下传递字符串和整数? – pruthvi