慕仔6258935
2018-01-08 13:14
activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=findViewById(R.id.et_input);
manager=getFragmentManager();
transaction=manager.beginTransaction();
transaction.add(R.id.content_layout,new ResultFragment());
transaction.commit();
}
// 通过点击事件将edittext中的内容传递给Resultfagment
public void send(View view) {
/*
* 1.获取输入框输入的内容
* */
String info=editText.getText().toString().trim();
// 创建bundle对象,将需要传递的数据存储到bundle中 然后调用fragment的setArguments()方法传递bundle
ResultFragment rf=new ResultFragment();
Bundle bundle=new Bundle();
bundle.putString("info",info);
rf.setArguments(bundle);
manager=getFragmentManager();
transaction=manager.beginTransaction();
transaction.replace(R.id.content_layout,rf);
transaction.commit();
}
fragment:
public class ResultFragment extends android.app.Fragment {
private TextView textView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_result,null);
Bundle bundle=getArguments();
String info=bundle.getString("info");
textView=view.findViewById(R.id.tv_result);
textView.setText(info);
return view;
}
logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
自己百度查了一下,好像是由于activity执行onCreate方法的时候fragment就已经被实例化,即使在下面执行如下代码片,已经被绑定的fragment也无法拿到bundle。我把oncreate中去掉了Fragment的绑定,测试可行。参考来源:https://www.jianshu.com/p/14170fd7d4bf
Fragment应用下
6789 学习 · 14 问题
相似问题