开发者

Android List with Image - How to implement

I'm looking for a clear way to es开发者_如何转开发tablish the XML resource for a list of strings with an image attached to it. Should I use attributes? What is the best practice?


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>

In 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);

The classes

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) {

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜