在fragment中 String info=bundle.getString("info");報錯
?
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
2018-01-08
自己百度查了一下,好像是由于activity執行onCreate方法的時候fragment就已經被實例化,即使在下面執行如下代碼片,已經被綁定的fragment也無法拿到bundle。我把oncreate中去掉了Fragment的綁定,測試可行。參考來源:https://www.jianshu.com/p/14170fd7d4bf