2016-04-11 134 views
2

我有數據綁定中的列表視圖問題,因爲我不知道如何在視圖模型中設置自定義ArrayAdapter,以及如何在視圖模型中添加onItemClick偵聽器。有人可以展示如何做到這一點?互聯網對此的信息很少。Java Android數據綁定ListView

回答

1

只需設置ListView的適配器即可。 R.id.listview必須引用您在佈局中明確定義的ListView和R.layout.listviewrow到行應該具有的佈局。此外,將一個新的onItemClickListener實例添加到ListView。

MyCustomArrayAdapter adapter = new MyCustomArrayAdapter(getActivity(), R.layout.listviewrow); 
ListView lv = (ListView) getActivity().findViewById(R.id.listview); 
lv.setAdapter(adapter); 

lv.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      //perform desired action here 
     } 
    }); 

適配器本身應該是這個樣子:

public class MyCustomArrayAdapter extends ArrayAdapter<Item> { 

    public MyCustomArrayAdapter(Context context, int resource) { 
     super(context, resource); 
    } 

    public MyCustomArrayAdapter(Context context, int resource, List<Item> items) { 
     super(context, resource, items); 
    } 

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

     View v = convertView; 

     if (v == null) { 
      LayoutInflater vi; 
      vi = LayoutInflater.from(getContext()); 
      v = vi.inflate(resource, null); 
     } 

     Item item = getItem(position); 

     if (item != null) { 
      TextView tvFirstName = (TextView) v.findViewById(R.id.firstName); 
      TextView tvLastName = (TextView) v.findViewById(R.id.lastName); 

     if (tvFirstName != null) { 
      tvFirstName.setText(item.getFirstName()); 
     } 

     if (tvLastName != null) { 
      tvLastName.setText(item.getLastName); 
     } 
    } 

    return v; 
} 
+0

確定。我明白。 – zeed94