4

「複雑な」データの配列をListViewにマップしたいと思います。非常に単純化された形式では、私のデータモデルは次のようになります。

class ListPlacesValues {

  String idObject;
  String name;
  String city;
  String country;
  ArrayList<String> classification;
  double distance_quantity;
  DistanceUnit distance_unit;
            [...more stuff ...]
}

複雑なデータをHashListに変換してから、SimpleAdapterを使用できることはわかっています。

   SimpleAdapter mAdapter = new SimpleAdapter(
     this,
     hashList,
     R.layout.places_listitem,
     new String[] { "name", "city", "country"}, 
     new int[] { R.id.name, R.id.city, R.id.country}
   );  

ただし、データモデルを直接使用したいのですが、どこからどのように開始すればよいかわからないため、最終的には次のようなことができます。

ArrayList<ListPlacesValues> values = getData();  
MyAdapter mAdapter = new MyAdapter(
          this,
          values,
          R.layout.places_listitem,
          ListPlacesValues { values.name, values.city, values.country}, 
          new int[] { R.id.name, R.id.city, R.id.country}
);  

解決策:このAndroid APIサンプル(List14)を見つけました。これは非常に役に立ちました。

4

2 に答える 2

4

ArrayAdapterを拡張できます。これがあなたのためのコード例です。この例では、SearchItemはカスタムPOJOです。基本的に、getView()メソッドをオーバーライドして、行レイアウトを拡張し、アイテムのリストと現在の位置に基づいて値を入力することにより、行を構築する必要があります。

class SearchItemsAdapter extends ArrayAdapter<SearchItem> {
Activity context;
List<SearchItem> items;
SearchHeader header;

@SuppressWarnings("unchecked")
public SearchItemsAdapter(final Activity context,
        final Map<SearchHeader, List<SearchItem>> result) {
    super(context, R.layout.item, (List) ((Object[]) result.values()
            .toArray())[0]);
    this.context = context;
    this.header = result.keySet().iterator().next();
    this.items = result.get(this.header);
}

@Override
public View getView(final int position, final View convertView,
        final ViewGroup parent) {
    final View view = this.context.getLayoutInflater().inflate(
            R.layout.item, null);
    final SearchItem item = this.items.get(position);
    ((TextView) view.findViewById(R.id.jt)).setText(item.jt);
    ((TextView) view.findViewById(R.id.dp)).setText(item.dp);
    ((TextView) view.findViewById(R.id.cn)).setText(item.cn);
    ((TextView) view.findViewById(R.id.loc)).setText(item.loc.name);
    final TextView body = ((TextView) view.findViewById(R.id.e));
    body.setText(item.e);
    body.setTag(item.src[0]);
    ((TextView) view.findViewById(R.id.src)).setText(item.src[1]);
    return view;
}
}
于 2009-10-20T17:30:29.347 に答える
1

リンクしたサンプルのconvertViewには1つの落とし穴があります

if(convertView != null){ //reuse
   convertView.setAnimation(null);
   convertView.setAnyCustomFieldsIdontWantFilledWithData(null);
}

すべてのアニメーションまたは未使用のフィールドをnullに設定する必要があります。そうしないと、アイテムにデータが含まれている可能性があります。

于 2009-10-22T11:16:23.403 に答える