ListView, OnItemClick not being called?

2020-08-01 05:54发布

问题:

I have a FragmentActivity that controls a ListFragment; that ListFragment contains a generic ListView, Adapter, and draws an ArrayList from a Singleton that I have created.

When in the onCreateView method of my ListFragment I put the following code:

public View onCreateView(LayoutInflater viewInflation, ViewGroup container,
        Bundle SavedInstantState) {
    cycleviewfragment = viewInflation.inflate(
            R.layout.cycleviewfragment_page, container, false);
    context = getActivity().getApplicationContext();
    Singleton mySingleton = Singleton.getInstance();
    basicList = (ListView) cycleviewfragment.findViewById(android.R.id.list);
    adapter = new ArrayAdapter<listControlObject>(getActivity()
            .getApplicationContext(), android.R.layout.simple_list_item_1,
            mySingleton.getA1());

    this.setListAdapter(adapter);

    addButton = (Button) cycleviewfragment.findViewById(R.id.addbutton);

    addButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(getActivity(),
                    listaddactivity.class);
            getActivity().startActivity(myIntent);
        }

    });

    basicList.setOnItemClickListener(new ListView.OnItemClickListener(){
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    Log.d("basicListtester", "Testing onClickItem call");
                    Intent myIntent = new Intent(getActivity(),
                            listdetailactivity.class);
                    myIntent.putExtra("selectedObjectIndex",arg2);
                    getActivity().startActivity(myIntent);

                }

            });

    adapter.notifyDataSetChanged();
    return cycleviewfragment;
}

Any ideas as to why when I add items to my list they do not react and the OnItemClick is not called?

Thanks guys.

[Update]

I tried implementing it with basicList.setAdapter(adapter); which still did not work.

also tried having my ListFragment implement OnItemClickListener and added the method to the class; which did not work either.

回答1:

Since you use ListFragment you shouldn't set onItemClickListener to your list. There is already a method in ListFragment that you should override.

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    //Do your thingy.
}


回答2:

Use

basicList.setListAdapter(adapter);

instead of

this.setListAdapter(adapter);

Use same instance of ListView for setting Adapter and setOnItemClickListener.



回答3:

you should override onListItemClick, since your class extends ListFragment. From the doc:

This method will be called when an item in the list is selected. Subclasses should override.

Here the documentation