2011-05-25 58 views
4

以下是我的代碼:安卓:ListView的onItemClick()事件沒有得到所謂的

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); 
    } 
} 

當我在ListView點擊一排,我看不出有任何吐司。有人可以告訴我我在哪裏犯了一個錯誤。

在此先感謝。

+1

別人可能會轉起來很快解決這個問題,而只是提的是:放置一個斷點'onListItemClick()'和運行在調試模式將允許您以確保方法是否被稱爲所有,這可能會縮小可能出現的問題的範圍。 – 2011-05-25 17:27:34

+0

@Viking:我在'onListItemClick()'處添加了一個斷點,我發現當我單擊列表視圖行時,控件不會到達那裏。可以告訴我可能有什麼錯誤? – 2011-05-25 17:35:28

+0

我在這裏找到了這個問題的解決方案:http://stackoverflow.com/questions/5551042/onitemclicklistener-not-working-in-listview-android – 2014-03-01 15:27:35

回答

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 
} 
4

我有一個類似的問題,發現從我的列表項刪除android:clickable="true"之後,onListItemClick()被觸發就好了。我希望這有幫助。

1

我也有這個問題。我通過從佈局XML中的TextView中移除這個來解決它。

android:textIsSelectable="true"