2014-02-19 100 views
0

我有兩個ListViews在我的活動中使用相同OnItemClickListener。有什麼方法可以確定我現在按哪個ListViews元素?我已使用此代碼:Android識別listView使用onItemClick監聽器

@Override 
public void onItemClick(AdapterView<?> list, View view, int position, 
     long id) { 


    if (view.getId() == R.id.listDictionary) { 
    // TODO Auto-generated method stub 


    Intent intent = new Intent(MainActivity.this, WordActivity.class); 
    DictionaryListElement ele = (DictionaryListElement) dictionaryList 
      .getAdapter().getItem(position); 
    intent.putExtra("word", ele.getWord()); 

    startActivity(intent); 
    } else if (view.getId() == R.id.listFavourites) { 
     Intent intent = new Intent(MainActivity.this, WordActivity.class); 
     String ele = (String)favouritesList.getAdapter().getItem(position); 
     intent.putExtra("word", ele); 
     startActivity(intent); 

    } 
} 

但它不工作。我認爲它得到每個按下的元素不是ListViews

+1

什麼是錯在上面的代碼? – Raghunandan

+0

嘗試使用列表視圖ID不是view.getId() – Abx

回答

1

您應該使用的ListView的ID(這裏ListView作爲AdapterViewonItemClick()傳遞),而不是View,因爲這View的ID是ListView項目。

if(list.getId() == R.id.listDictionary) { 
    // item in dictionary list is clicked 
} else if (list.getId() == R.id.listFavourites) { 
    // item in favourite list is clicked 
} 
+0

一樣複雜我明白,問題是問,爲什麼代碼不工作,你的答案是完全正確的,但我不明白爲什麼會鼓勵繼續使用這種混亂的邏輯。 –

+0

@AlexanderGavrilov爲什麼你覺得這段代碼很混亂?但對我來說,這是一個代碼的可重用性和最小代碼和適當的文檔代碼是從來沒有雜亂... –

+0

我只注意列表參數現在只有大聲笑。 –

1

爲什麼你需要相同的偵聽器,如果你區分邏輯與ifs?爲每個視圖創建單獨的偵聽器。這將是更乾淨的代碼,並應該工作。

// dictionary listener 
@Override 
public void onItemClick(AdapterView<?> list, View view, int position, 
     long id) { 
    Intent intent = new Intent(MainActivity.this, WordActivity.class); 
    DictionaryListElement ele = (DictionaryListElement) dictionaryList 
      .getAdapter().getItem(position); 
    intent.putExtra("word", ele.getWord()); 

    startActivity(intent); 
} 

// favorites listener 
    @Override 
     public void onItemClick(AdapterView<?> list, View view, int position, 
       long id) { 
      Intent intent = new Intent(MainActivity.this, WordActivity.class); 
      String ele = (String)favouritesList.getAdapter().getItem(position); 
      intent.putExtra("word", ele); 
      startActivity(intent); 
     } 
+0

謝謝你的回答。我的想法變得像Android代碼 –

0
switch(list.getId()){ 
case R.id.listDictionary: 
//listDictionary related action here 
break; 

case R.id.listFavourites: 
// listFavourites related action here 
break; 

default: 
    break; 
}