ListFragment的getListAdapter()返回null,getListView有效

时间:2014-09-22 16:33:19

标签: android android-listfragment

按照标题,我陷入了这个荒谬的问题

我有一个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并使之前的List无效,所以我正在调用:

AlarmsAdapter mAdapater = (AlarmsAdapter) mAlarmsListFragment.getListAdapter();
mAdapater.add(a);
mAdapater.notifyDataSetChanged();

事情是,我得到一个nullPointerException,因为getListAdapter()返回null,而getListView()工作正常..可能导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:2)

您需要在setListAdapter上致电ListFragment,即:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setRetainInstance(true);

    mAdapter = new AlarmsAdapter(getActivity(), R.layout.alarm_card_item, alarmsList);

    setListAdapter(mAdapter);
}

您无需在ListView上调用setAdapter。 ListFragment将处理它。