按標題,我被堵在這個荒謬的問題getListAdapter()從ListFragment返回null,getListView工作
我有一個ListFragment,這裏的精簡代碼:
public class AlarmsListFragment extends ListFragment implements AbsListView.OnItemClickListener {
public ListAdapter mAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mAdapter = new AlarmsAdapter(getActivity(), R.layout.alarm_card_item, alarmsList);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_alarms_list, container, false);
mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
return view;
}
}
而且然後有一個活動:
public class MainActivity extends Activity implements AlarmsListFragment.OnAlarmSelectedListener {
ListFragment mAlarmsListFragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getFragmentManager();
mAlarmsListFragment = (ListFragment) fm.findFragmentByTag(ALARM_LIST_TAG);
if (mAlarmsListFragment == null)
{
mAlarmsListFragment = new AlarmsListFragment();
getFragmentManager().beginTransaction()
.add(R.id.listContainer, mAlarmsListFragment, ALARM_LIST_TAG)
.commit();
}
}
後來,onOptionsItemSelected,我有一些代碼,需要將項目添加到ListAdapter和無效前面的列表,所以我打電話:
AlarmsAdapter mAdapater = (AlarmsAdapter) mAlarmsListFragment.getListAdapter();
mAdapater.add(a);
mAdapater.notifyDataSetChanged();
事情是,我得到一個NullPointerException因爲getListAdapter()返回null,而getListView()工作正常..什麼可能導致這個錯誤?
您是否嘗試過在您的listfragment上創建自己的getadapter方法?並返回mAdapter? – 2014-09-22 16:36:51
這是我見過的最快的正確回覆,mAlarmsListFragment.getListView()。getAdapter()工作,大小寫關閉......但爲什麼getListAdapter()在這種情況下工作? – Mdk 2014-09-22 16:37:08