2010-06-07 127 views
8

我有下面的代碼訪問ListView的項目值到字符串中,並顯示在警報?如何獲得在Android中單擊的Listview項目的值?

ListView shot = getListView(); 
shot.setOnItemClickListener(this); 

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { 

    String S = arg1.getContext().toString(); 
    AlertDialog.Builder alertbox = new AlertDialog.Builder(this); 

    // set the message to display 
    alertbox.setMessage(S).show();  
} 
+1

請多花點心思問問題。我無法完全理解你的問題。你想做什麼?什麼工作什麼不是? – Janusz 2010-06-07 10:02:59

+1

提示:請勿使用'arg0','arg1'等作爲參數名稱。它使源代碼完整無法讀取。其中之一就是你正在尋找的信息,所以如果你使用了正確的名字,你就不需要問這個問題。 – RoToRa 2010-06-07 10:18:20

回答

16

也許這個例子可以幫助你

lv.setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> parent, View view, 
     int position, long id) { 
     // When clicked, show a toast with the TextView text 
     Toast.makeText(getApplicationContext(), ((TextView) view).getText(), 
      Toast.LENGTH_SHORT).show(); 
    } 
    }); 

https://developer.android.com/reference/android/widget/ListView.html

0

也許你可以試試這個

String data = (String)shot.getItemAtPosition(arg2); 
AlertDialog.Builder adb = new AlertDialog.Builder(arg1.getContext());    
adb.setMessage(data).show(); 
10

這給你的項目的精確值點擊。檢查日誌

ListView shot = getListView(); 
shot.setOnItemClickListener(this); 

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

    String val =(String) parent.getItemAtPosition(position); 
    System.out.println("Value is "+val); 
} 
+0

爲我啓動了一個ClassCastException! – bofredo 2013-04-03 13:33:43

相關問題