Можно ли установить динамический значок из XML в SimpleAdapter? - PullRequest
1 голос
/ 29 марта 2012

Я бы хотел использовать SimpleAdapter вместо настройки ArrayAdapter. Все работает, кроме значка, который связан с каждой строкой. Значок относится непосредственно к этикетке. ТАК, в зависимости от метки, значок может отличаться.

Вот пример XML

<profile>
<id>16</id>
<name>Random Name</name>
<site>Random URL</site>
<icon>R.drawable.random_icon</icon>
</profile>

Мой пользовательский макет строки

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" >

<ImageView
    android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@+id/label" />

<ImageView
    android:id="@+id/arrow"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/arrow" />

</LinearLayout>

Теперь вот где я анализирую свой XML и настраиваю свой адаптер (отредактированный только для соответствующих частей):

        NodeList children = doc.getElementsByTagName("profile");

    for (int i = 0; i < children.getLength(); i++) {

            HashMap<String, String> map = new HashMap<String, String>();

                    Element e = (Element) children.item(i);

                    map.put("id", ParseXMLMethods.getValue(e, "id"));
        map.put("name", ParseXMLMethods.getValue(e, "name"));
        map.put("site", ParseXMLMethods.getValue(e, "site"));
        map.put("icon", ParseXMLMethods.getValue(e, "icon"));
        mylist.add(map);
    }

           View header = getLayoutInflater().inflate(R.layout.header, null, false);

       ListAdapter adapter = new SimpleAdapter(this, mylist,
            R.layout.rowlayout, new String[] { "name", "icon" }, new int[] { R.id.label, R.id.icon });


    final ListView lv = getListView();
    lv.addHeaderView(header, null, false);
    lv.setSelector(R.color.list_selector);
    setListAdapter(adapter);

Программа не падает. Все выглядит как есть, я даже анализирую «сайт», поэтому при щелчке строки открывается веб-представление. Я просто не могу показать значок. Это возможно даже с SimpleAdapter?

ОБНОВЛЕНИЕ: Здесь переопределен метод getView ():

public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);

    int idImage = context.getResources().getIdentifier("icon","drawable", context.getPackageName());

    //   ????????

    return view;
}

1 Ответ

0 голосов
/ 29 марта 2012

Я могу порекомендовать вам добиться этого с помощью метода getIdentifier из ресурсов расширенного SimpleAdapter. Но для этого сначала нужно немного изменить xml:

Вместо того, чтобы сохранять программируемую ссылку изображения в ваш XML, вы должны просто сохранить имя файла:

<profile>
  <id>16</id>
  <name>Random Name</name>
  <site>Random URL</site>
  <icon>random_icon</icon>
</profile>

Теперь расширьте свой SimpleAdapter до своего собственного класса адаптера и переопределите метод getView. В этом методе вы можете восстановить идентификатор ресурса из имени и установить его в свой ImageView:

int idImage = context.getResources().getIdentifier("nameOfResource", "drawable", context.getPackageName());

Обновление

public class MyAdapter extends SimpleAdapter {

    private Context context;

    List<HashMap<String, String>> lstData = new ArrayList<HashMap<String,String>>();

    public MyAdapter(Context context, List<HashMap<String, String>> items) {
        super(context, items, android.R.id.text1, R.layout.rowlayout, new String[] { "name", "icon" }, new int[] { R.id.label, R.id.icon });

        this.context = context;
        lstData = items;
    }




    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;

        //smart initialization      
        if(convertView == null){
            LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflator.inflate(R.layout.rowlayout, parent, false);

            holder = new ViewHolder();
            holder.title = (TextView) convertView.findViewById(R.id.label);
            holder.img = (ImageView) convertView.findViewById(R.id.icon);
            convertView.setTag(holder);
        }
        else
            holder = (ViewHolder) convertView.getTag();

        //get item
        HashMap<String, String> map = lstData.get(position);

        //setting title
        holder.title.setText(map.get("name"));

        int idImage = context.getResources().getIdentifier(map.get("icon"),"drawable", context.getPackageName());
        holder.img.setImageResource(idImage);

        return convertView;
    }



    //this is better approach as suggested by Google-IO for ListView
    private static class ViewHolder{
        TextView title;
        ImageView img;
    }

}

* этот код класса является справочным для вас, чтобы увидеть, как должен выглядеть ваш адаптер. Более подходящий способ - использовать ArrayAdapter, но поскольку вы уже используете SimpleAdapter, я просто расширил его возможности

...