Android Studio中的ListView标题在所有标题中始终只有一个图像。我可以将代码中图像副本的x倍减少到1倍吗

时间:2018-09-03 07:38:17

标签: android listview

在Android ListView中,始终在所有标题中重复一个图像。如何将代码中的图像复制次数从x减少到1倍?

如下面给出的代码:

int[] fruitImages = {R.drawable.ic_chevron_right,R.drawable.ic_chevron_right,R.drawable.ic_chevron_right,R.drawable.ic_chevron_right,R.drawable.ic_chevron_right};

在这段代码中,我每次都复制相同的图像代码,即:

snprintf("%d

我想设置许多重复,例如x(乘以可绘制图像)。有可能吗?

可以从LarnTech获得GitHub项目。在这个项目中,我的图像是一个箭头。我可以通过重复这些操作来做到这一点,但我很好奇它是否可以以一种清晰的方式完成。

2 个答案:

答案 0 :(得分:1)

只需在适配器的构造函数中单独传递您的水果数组,然后使用imageView.setResource(R.drawable.ic_chevron_right)设置可绘制对象

 public class SimpleArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] fruitNames;

    public MySimpleArrayAdapter(Context context, String[] fruitNames) {
        super(context, -1, values);
        this.context = context;
        this. fruitNames = fruitNames;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
        textView.setText(fruitNames[position]);//fruitName

        imageView.setImageResource(R.drawable.ic_chevron_right); //just set the image in the adapter


        return rowView;
    }
}

答案 1 :(得分:0)

我可以看到您的github项目,数组中的图像不同。 但是在这里,所有图像都是相同的。

如果您不想创建相同图像的数组,则可以在此处仅使用一个变量。喜欢:

int fruitImage = R.drawable.ic_chevron_right;

,它可以像{p>那样用于getView()的{​​{1}}中

CustomAdapter

但是如果您必须在每个视图中使用不同的图像,则需要使用array或使用ArrayList。