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">
<FrameLayout
android:id="@+id/flNewItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
<FrameLayout
android:id="@+id/flItemList"
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 fragment
View 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 name
void 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,程序正常
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.athand.master4.todolistfragment.NewItemFragment"
android:id="@+id/NewItemFragment"/>
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.athand.master4.todolistfragment.ToDoListFragment"
android:id="@+id/ToDoListFragment"/>
这个是怎么一回事呢
大家讲道理2017-04-17 17:38:24
우선 한 가지 점을 기억할 수 있습니다. findFragmentById는 xml 레이아웃에 선언된 조각에 더 적합합니다.
안드로이드 댓글에는 트랜잭션에 추가된 프래그먼트에도 적용 가능하다고 되어 있지만 commit 메서드는 동기 프로세스가 아니라 비동기 프로세스입니다. 따라서 조각 핸들을 직접 가져올 수 없으므로 널 포인터가 발생합니다.
怪我咯2017-04-17 17:38:24
fm.findFragmentById(R.id.flItemList)
은 id
을 검색하여 fragment
인스턴스를 반환하지만 R.ud.flItemList
자체는 fragment
이 아니므로 당연히 toDoListFragment
은 비어 있습니다. 따라서 toDoListFragment.setListAdapter(aa);
은 java.lang.NullPointerException
예외를 보고합니다.