带图像的Android列表 - 如何实现

时间:2011-04-06 02:08:27

标签: android

我正在寻找一种明确的方法来为附加了图像的字符串列表建立XML资源。 我应该使用属性吗?什么是最佳做法?

1 个答案:

答案 0 :(得分:0)

list_layout.xml     

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <ListView android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

row_layout.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

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

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

</LinearLayout>

在onCreate()

setContentView(R.layout.list_layout);
ListView lv = (ListView) findViewById(R.id.list);
List<ListRow> list = new ArrayList<ListRow>();

for ( loop through your data ) {
     list.add(new ListRow("text", R.drawable.image));
}

YourAdapter adapter = new YourAdapter(this, list);
lv.setAdapter(adapter);

课程

class ListRow {
    private String text;
    private int resource;

    public ListRow(String text, int resource) {
        super();
        this.text = text;
        this.resource = resource;
    }

    public int getText() {
        return text;
    }
    public int getResource() {
        return resource;
    }
}

class YourAdapter extends BaseAdapter implements OnClickListener {
    private Context context;

    private List<ListRow> theList;

    public YourAdapter (Context context, List<ListRow> theList) {
        this.context = context;
        this.theList = theList;
    }

    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ListRow row = theList.get(position);

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.row_layout, null);
        }

        TextView tv = (TextView) convertView.findViewById(R.id.row_text);
        tv.setText(row.getText());

        ImageView iv = (ImageView) convertView.findViewById(R.id.row_image);
        iv.setBackgroundResource(row.getResource());

        return convertView;
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
}