Android: Listview's onItemClick() event not getting called

限于喜欢 提交于 2019-12-10 15:38:57

问题


Following is my code :

public class TestActivity extends ListActivity {

    private Cursor cursor;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        fillData(); 
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        // Get the item that was clicked
        Object o = this.getListAdapter().getItem(position);
        String keyword = o.toString();
        Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
                .show();
    }

    private void fillData() {
        TermsData_DataHelper termsDataHelper = new TermsData_DataHelper(
                TestActivity.this);
        cursor = termsDataHelper.fetchAllCategories();
        startManagingCursor(cursor);

        String[] names = new String[] { "name" };
        int[] to = new int[] { R.id.label };

        // Now create an array adapter and set it to display using our row
        SimpleCursorAdapter categories = new SimpleCursorAdapter(this,
                R.layout.terms_row, cursor, names, to);
        setListAdapter(categories);
    }
}

When I click on a row in the listview, I don't see any Toast. Can anybody tell me where am I making a mistake.

Thanks in advance.


回答1:


I was having a similar problem and found that after removing android:clickable="true" from my list items, the onListItemClick() was being triggered just fine. I hope this helps.




回答2:


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

    String mString = parent.getItemAtPosition(position).toString();
    //will give you the text of current line or
    int i = parent.getItemAtPosition(position);
    //if you want just position number
}



回答3:


The solution is to override protected void onListItemClick (ListView l, View v, int position, long id) method.




回答4:


I had this problem also. I solved it by Removing this from my TextView in the the layout XML.

    android:textIsSelectable="true"


来源:https://stackoverflow.com/questions/6128219/android-listviews-onitemclick-event-not-getting-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!