You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何不新建自定义类在ListView文本旁添加图标

无自定义类实现ListView列表项带图标方案

不需要额外新建独立的自定义适配器类文件,直接在现有代码基础上修改即可实现需求,具体调整如下:

  • 首先修正原有图标数组的语法错误,原写法不符合Java数组初始化规范,需要和文本数组按顺序一一对应存储图标资源ID
  • 初始化ArrayAdapter时使用匿名内部类重写getView方法,直接调用TextView自带的复合图标方法设置对应位置的图标,全程不需要新建单独的类文件
  • 可按需设置图标和文本的间距,避免内容贴靠

修正后可直接运行的完整代码

// 注意:数组顺序和下方列表文本一一对应,替换为你实际的图标资源即可
int[] icons_lv = new int[]{
        R.drawable.icon_1,
        R.drawable.icon_2,
        R.drawable.icon_3
};

listView = findViewById(R.id.list_view_app_ifo);
String[] values = new String[] {
        "Check for an update" ,
        "Rate App",
        "Tell us about your feedback"
};

ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values){
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View itemView = super.getView(position, convertView, parent);
        TextView itemText = itemView.findViewById(android.R.id.text1);
        // 参数依次对应左、上、右、下四个位置的图标,仅需要左侧图标其余传0即可
        itemText.setCompoundDrawablesWithIntrinsicBounds(icons_lv[position], 0, 0, 0);
        // 设置图标和文字的间距,单位为px,可按需调整数值
        itemText.setCompoundDrawablePadding(24);
        return itemView;
    }
};
listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position ==0) {
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName()));
            startActivity(intent);
        }
        if (position ==1) {
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName()));
            startActivity(intent);
        }
    }
});

注意事项

  • 图标数组长度必须和文本数组长度完全一致,顺序一一对应,否则会触发数组越界崩溃或者图标匹配错误
  • 如果需要把图标放在文本右侧/上/下侧,只需要调整setCompoundDrawablesWithIntrinsicBounds方法对应位置的参数即可
  • 如果需要更精准的间距适配,可以把dp值转成px单位再传入setCompoundDrawablePadding方法

内容的提问来源于stack exchange,提问作者سامي عبدالله علي المصباحي

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 22:54:37