扩展ArrayAdapter并覆盖getView时

扩展ArrayAdapter并覆盖getView时

本文介绍了扩展ArrayAdapter并覆盖getView时,传递resource/textViewResourceId参数是否完全多余?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为ListViews定制自定义ArrayAdapters,在扩展它们时,我总是一直简单地将-1(不存在的资源ID)作为super的资源参数传递.当您还覆盖getView时,将其他任何内容传递给它是否有任何潜在的好处?

I've been messing around with custom ArrayAdapters for ListViews a bit, and when extending them I've always simply passed -1 (A non-existent resource id) as the resource argument to super. Are there any potential benefits (at all) to passing anything else in it's place when you also override getView?

推荐答案

好的.如果传递您的实际布局和TextView资源ID,则可以让super.getView()方法处理View膨胀并在单个TextView上分配文本.然后,您的getView()替代项仅需要填充空白".

Sure. If you pass your actual layout and TextView Resource ID, you can let the super.getView() method handle the View inflation and assigning the text on a single TextView. Then your getView() override would just need to "fill in the blanks".

例如,假设我们有以下简单的列表项类:

For example, say we have the following simple list item class:

public class Item {
    String text;
    int imageResId;

    public Item(String text, int imageResId) {
        this.text = text;
        this.imageResId = imageResId;
    }

    @Override
    public String toString() {
        return text;
    }
}

还有一个简单的项目布局,如下所示:

And a simple item layout like so:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical">

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

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

</LinearLayout>

然后我们的ArrayAdapter子类可能就是这样:

Then our ArrayAdapter subclass could be simply this:

public class MyAdapter extends ArrayAdapter<Item> {
    public MyAdapter(Context context, List<Item> items) {
        super(context, R.layout.list_item, R.id.item_text, items);
    }

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

        ((ImageView) v.findViewById(R.id.item_image))
            .setImageResource(getItem(position).imageResId);

        return v;
    }
}

请注意,我们在Item类中实现了toString()覆盖,以为ArrayAdapter提供正确的String.

Note that we implement a toString() override in our Item class to provide the correct String to ArrayAdapter.

这篇关于扩展ArrayAdapter并覆盖getView时,传递resource/textViewResourceId参数是否完全多余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:18