我有两个动态片段与一个活动相关联,我试图使用Bundle将一个文本从第一个片段传递到第二个片段,但是我得到了空指针异常。它是在两个片段之间传递String的正确方法吗?以下是我的代码:
First Fragment
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_main, container, false);
String text = "GetThisStringInSecondFragment";
TextView txtView = null;
txtView = (TextView) view.findViewById(R.id.firstfragmenttext);
txtView.setText(text);
Bundle bundle = new Bundle();
bundle.putString("HI", text);
return view;
}
}
第二片段
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_secondmain,
container, false);
TextView txtView = null;
txtView = (TextView) view.findViewById(R.id.secondfragmenttext);
Bundle bundle = this.getArguments();
String myInt = bundle.getString("HI");
txtView.setText(myInt);
return view;
}
}
活动
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnLoad = (Button) findViewById(R.id.btn_load);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FirstFragment hello = new FirstFragment();
fragmentTransaction.add(R.id.fragment_container, hello, "HELLO");
fragmentTransaction.commit();
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
SecondFragment hello2 = new SecondFragment();
fragmentTransaction2.add(R.id.fragment_container, hello2, "HELLO");
fragmentTransaction2.commit();
}
};
btnLoad.setOnClickListener(listener);
}
}
答案 0 :(得分:0)
您正在第二个片段中执行getArguments,但是您从哪里发送第一个片段的参数。您可以在此处使用Interface并在活动中定义它。从activity,您可以使用setArgument()方法获取第二个片段。
请查看以下链接以获取更多详细信息和步骤。 https://developer.android.com/training/basics/fragments/communicating.html