2011-11-11 46 views
0

我不知道爲什麼我得到它此行的代碼(其中箭頭)拋出ClassCastException在java.lang.String中Android中

protected void onListItemClick(ListView l, View v, int position, long id) { 
---> App selection = (App) l.getItemAtPosition(position); 

定製ArrayAdapter:

public class MyCustomAdapter extends ArrayAdapter<String>{ 

private ArrayList<String> myarr = new ArrayList<String>(); 
private LayoutInflater inflater; 

//objects = array of whatever you want to add to the list 
public MyCustomAdapter(Context context, 
     int textViewResourceId, List<String> objects) { 
    super(context, textViewResourceId, objects); 
    myarr = (ArrayList<String>) objects; 
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 

     View row = convertView; 
     if(row==null){ 
     row=inflater.inflate(R.layout.list_row, parent,false); 
     } 

     ((TextView)row.findViewById(R.id.rowtextview)).setText(myarr.get(position)); 

     return row; 
    } 

這是做這項工作的arrayadapter。我假設問題在這裏。

+0

這裏應用意味着.. –

+0

它,我創造了一個自定義類。我不明白爲什麼我不能將它轉換爲l.getItemAtPosition返回的對象 – volk

回答

3

您必須在您的ListView中保存String。它給人的異常,因爲它無法在你的myarrStringApp

編輯
的對象都顯示在您的ListView。這些物體都是String s。在出現異常的行中,您嘗試將Stringposition轉換爲App。它不能這樣做,所以你得到的例外。所以,試試這個:

String selection = (String) l.getItemAtPosition(position); 

EDIT2
變化myarr

private ArrayList<App> myarr = new ArrayList<App>(); 

更改以下行:

((TextView)row.findViewById(R.id.rowtextview)).setText(myarr.get(position).getText()); 

添加App類:

public String getText(){/*...*/} 
public void setText(String text){/*...*/} 
public String toString(){ /*...*/} 
+0

你能解釋一下你的意思嗎?因爲我有一個自定義的arrayadapter設置,並且list_row.xml包含了列表中的一行應該是什麼樣子。我明白你的意思,但我不知道要找什麼 – volk

+0

請發佈你的列表適配器代碼,和xml文件 – Caner

+0

確定它。給它一看。和你想看到哪個xml文件? – volk

0

如果使用自定義這樣

MyFont f = fontArray[pos]; 
selected_font = f.getValue(); 
相關問題