ListView 的自定义适配器忽略设置值

Custom adapter for ListView ignores set values

我要创建一个 ListView 标签和图标。

这是我所做的:
我创建了一个名为 cardList 的空白 ListView
我创建了一个扩展 ArrayAdapter<String> 的自定义视图
并且我已将 cardList 设置为该自定义视图:

cardList = findViewById(R.id.cards_list);
CustomView customView = new CustomView(this, names, images);
cardList.setAdapter(customView);

哪里

ListView cardList;
String[] names = {"Name1", "Name2", "Name3"};
Integer[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3};

CustomView class:

package ...

import ...

public class CustomView extends ArrayAdapter<String> {

    private String[] names;
    private Integer[] images;
    private Activity context;

    CustomView(Activity context, String[] names, Integer[] images) {
        super(context, R.layout.card_row, R.id.cardName, names);
        this.context = context;
        this.names = names;
        this.images = images;
    }

    @SuppressLint("InflateParams")
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View r = convertView;
        ViewHolder viewHolder;
        if (r == null) {
            LayoutInflater layoutInflater = context.getLayoutInflater();
            r = layoutInflater.inflate(R.layout.card_row, null, true);
            viewHolder = new ViewHolder(r);
            r.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) r.getTag();
        }
        viewHolder.name.setText(/*skipping: names[position]*/"Some text");
        viewHolder.name.setTypeface(Typeface.createFromAsset(AppName.assetManager, "fonts/prototype.ttf"));
        viewHolder.image.setImageResource(images[position]);
        return super.getView(position, convertView, parent);
    }

    class ViewHolder {
        TextView name;
        ImageView image;
        ViewHolder(View v) {
            name = v.findViewById(R.id.cardName);
            image = v.findViewById(R.id.symbolImg);
        }
    }
}

现在,我故意这样写 viewHolder.name.setText(/*skipping: names[position]*/"Some text"); 行。结果是我的 ListView 显示了数组中的名称,尽管方法 setText("Some text") 应该改变它,并且没有图标和自定义字体。所以,这个部分有问题:

viewHolder.name.setText(/*skipping: names[position]*/"Some text");
viewHolder.name.setTypeface(Typeface.createFromAsset(AppName.assetManager, "fonts/prototype.ttf"));
viewHolder.image.setImageResource(images[position]);

调试表明应用程序通过了这个部分,但是所有应该在里面设置的东西都被忽略了。我错过了什么吗?

您的自定义视图被忽略,因为您的 return 父视图来自 getView 而不是您的

使用

return r;

而不是

return super.getView(position, convertView, parent);