Question

Usually I set my ItemClickListener using

list.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                    long x = MyActivity.this.myAdapter.getItemId(position); //to get the clicked item position
            }
        });

After setting my ListView etc.

Now I have to work on a code that use the list with default Android list adapter in this way

public class ListDefs extends ListActivity {
        private Defs defs;
        private ArrayAdapter<String> adapter;

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            defs = Note.defs;
            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, defs.lines);
            setListAdapter(adapter);
        }


    }

How to set a OnItemClickListener() in this scenario?

Was it helpful?

Solution

ListActivity has both a getListAdapter and getListView methods.

In your onCreate, after you call

setContentView(R.layout.list_activity); 

where R.layout.list_activity is your layout file for the activity that has a ListView tagged with the android list id like so (according to the docs)

<ListView
    android:id="@android:id/list"
    ... />

you can call

getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
    ...
    }
});

From the docs

ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "@android:id/list" (or list if it's in code)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top