android - fragement用fragmentmanger,fragmenttransaction添加到activity碰到问题

浏览:34日期:2022-12-04

问题描述

1.初学fragment,写了一小段代码,用fragmentmanger,fragmenttransaction添加到activity碰到问题

2.代码如下

activity的layout

<?xml version='1.0' encoding='utf-8'?><LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical'><FrameLayoutandroid: android:layout_width='match_parent'android:layout_height='match_parent'android:layout_weight='1'/> <FrameLayoutandroid: android:layout_width='match_parent'android:layout_height='match_parent'android:layout_weight='3'/></LinearLayout>

两个fragment的代码:

NewItemFragment:

public class NewItemFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = 'param1'; private static final String ARG_PARAM2 = 'param2'; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnAddNewItemListener mListener; public NewItemFragment() {// Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment NewItemFragment. */ // TODO: Rename and change types and number of parameters public static NewItemFragment newInstance(String param1, String param2) {NewItemFragment fragment = new NewItemFragment();Bundle args = new Bundle();args.putString(ARG_PARAM1, param1);args.putString(ARG_PARAM2, param2);fragment.setArguments(args);return fragment; } @Override public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2);} } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {// Inflate the layout for this fragmentView view=inflater.inflate(R.layout.new_item_fragment, container, false);final EditText etNewItem;etNewItem= (EditText) view.findViewById(R.id.etNewItem);etNewItem.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View view, int i, KeyEvent keyEvent) {if(keyEvent.getAction()==KeyEvent.ACTION_DOWN){ if((i==KeyEvent.KEYCODE_DPAD_CENTER) || (i==KeyEvent.KEYCODE_ENTER)) {if (mListener != null) { mListener.onAddItem(etNewItem.getText().toString());}etNewItem.setText('');return true; }}return false; }});return view; } @Override public void onAttach(Activity activity) {super.onAttach(activity);if (activity instanceof OnAddNewItemListener) { mListener = (OnAddNewItemListener) activity;} else { throw new RuntimeException(activity.toString() + ' must implement OnFragmentInteractionListener');} } @Override public void onDetach() {super.onDetach();mListener = null; } public interface OnAddNewItemListener {// TODO: Update argument type and namevoid onAddItem(String newItem); }}

ToDoListFragment:

public class ToDoListFragment extends ListFragment { public ToDoListFragment() { }}

activity的代码

public class MainActivity extends AppCompatActivity implements NewItemFragment.OnAddNewItemListener { ArrayList<String> newItems; ArrayAdapter<String> aa; @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);newItems=new ArrayList<>();aa=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,newItems);textView= (TextView) findViewById(R.id.tvSample);FragmentManager fm=getSupportFragmentManager();NewItemFragment newItemFragment= (NewItemFragment) fm.findFragmentById(R.id.flNewItem);if(newItemFragment==null){ FragmentTransaction ft=fm.beginTransaction(); ft.replace(R.id.flNewItem,new ToDoListFragment()); ft.commit();}ToDoListFragment toDoListFragment= (ToDoListFragment) fm.findFragmentById(R.id.flItemList);if(toDoListFragment==null){ textView.setText('todolistfragment'); FragmentTransaction ft=fm.beginTransaction(); ft.replace(R.id.flItemList,new ToDoListFragment()); ft.commit();}toDoListFragment.setListAdapter(aa); } @Override public void onAddItem(String newItem) {newItems.add(0,newItem);aa.notifyDataSetChanged(); }}

当程序运行toDoListFragment.setListAdapter(aa);,就跳出,就报空指针错误 Caused by: java.lang.NullPointerException at com.athand.master4.todolistfragment.MainActivity.onCreate(MainActivity.java:45)

如果layout不用frameLayout,直接用fragment,程序正常

<fragmentandroid:layout_width='match_parent'android:layout_height='wrap_content'android:name='com.athand.master4.todolistfragment.NewItemFragment'android: /> <fragmentandroid:layout_width='match_parent'android:layout_height='wrap_content'android:name='com.athand.master4.todolistfragment.ToDoListFragment'android: />

这个是怎么一回事呢

问题解答

回答1:

首先,可以记住一个观点:findFragmentById更多适应于xml布局中声明的fragment。

虽然android注释中说也适用于transaction中添加的fragment,但是commit方法不是一个同步的过程,而是异步的。所以你没法直接获取到fragment句柄,从而导致了空指针。

回答2:

fm.findFragmentById(R.id.flItemList)通过寻找id返回一个fragment实例,但是你的这个R.ud.flItemList本身就不是一个fragment,自然toDoListFragment为空。所以你的toDoListFragment.setListAdapter(aa);会报java.lang.NullPointerException异常。

相关文章: