2012-10-21 61 views
0

我創建了一個自定義ListView。列表中的每個項目都有一個imageView和兩個TextView。管理列表項ListView

的代碼是:

public class PersonalList extends ListActivity{ 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    String[] name= new String[] { "Mary", "Frank", 
      "John" }; 
    String[] surname = new String[] { "Ballak", "Doe", 
      "Strip"" }; 
    setContentView(R.layout.member_list); 

    MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, name, surname); 
    setListAdapter(adapter); 
} 

protected void onListItemClick(ListView l, View v, int position, long id) { 
    String name = (String) getListAdapter().getItem(position); 
    Toast.makeText(this, "selected item: "+name, Toast.LENGTH_LONG).show();  
    } 

} 

其中MySimpleArrayAdapter是:

public class MySimpleArrayAdapter extends ArrayAdapter<String> { 
     private final Context context; 
     private final String[] name; 
     private final String[] surname; 

     public MySimpleArrayAdapter(Context context, String[] name, String[] surname) 
     { 
      super(context, R.layout.list_row, name); 
      this.context = context; 
      this.name= name; 
      this.surname = surname; 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
     LayoutInflater inflater = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View rowView = inflater.inflate(R.layout.rowlayout, parent, false); 
     TextView nameView= (TextView) rowView.findViewById(R.id.label); 
     TextView surnameView= (TextView) rowView.findViewById(R.id.label1); 
     ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); 
     nameView.setText(name[position]); 
     surnameView.setText(surname[position]); 

     return rowView; 
     } 
    } 

調用從onListItemClick以下代碼:

Toast.makeText(this, "selected item: "+name, Toast.LENGTH_LONG).show(); 

我獲得的第一個項目中烤麪包的消息像這樣:

"selected item: Mary" 

如何才能獲得以下結果?

"selected item: Mary Ballak" 
+1

我強烈建議看Android的羅ain Guy [討論適配器和效率](http://www.google.com/events/io/2009/sessions/TurboChargeUiAndroidFast.html)的一些專業技巧,因爲我沒有使用ArrayAdapter的獨特方法擴展了BaseAdapter。 – Sam

回答

3

這將讓你第一&姓氏:

protected void onListItemClick(ListView l, View v, int position, long id) { 
    String name = (String) getListAdapter().getItem(position); 
    Toast.makeText(this, "selected item: " + ((TextView) v.findViewById(R.id.label)).getText().toString() + " " + ((TextView) v.findViewById(R.id.label1)).getText().toString(), Toast.LENGTH_LONG).show();  
    } 

另外 - 你可以從onItemClick獲得指標,並從陣列中的字符串(名稱/姓) - 如果你」 LL將數組保存爲您Activity

喜歡的東西的成員:String text = mName[position] + " " + msurName[position];

+0

謝謝。現在它運作良好。但爲什麼getListAdapter()。getItem(position);返回第一個字符串數組(名稱)的項目? – GVillani82

+0

適配器遍歷字符串的ArrayList。 getView()方法將被稱爲列表項的次數。在你的情況下 - 儘管你沒有像你這樣實現你的適配器,這個列表就是名字的列表。 P.S如果這個答案幫助你 - 請善待和接受..:0謝謝! – Givi