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

Android中AutoCompleteTextView绑定API数据显示对象地址问题求助

解决AutoCompleteTextView显示对象地址而非名称的问题

这个问题很常见,原因是你的DropdownVal类没有重写toString()方法,而ArrayAdapter默认会调用每个对象的toString()来生成下拉列表的显示文本,所以你看到的是对象的内存地址(比如com.yourpackage.DropdownVal@xxxxxx)。

下面给你两种简单的解决方案,选一种就行:

方案一:重写DropdownVal的toString()方法(最简便)

直接在你的DropdownVal类里添加toString()方法,让它返回你想要显示的ItemName:

public class DropdownVal {
    private String id;
    private String itemName;

    // 你的构造方法
    public DropdownVal(String id, String itemName) {
        this.id = id;
        this.itemName = itemName;
    }

    // 你的getter方法
    public String getId() { return id; }
    public String getItemName() { return itemName; }

    // 重写toString,返回要显示的名称
    @Override
    public String toString() {
        return itemName;
    }
}

这样ArrayAdapter就会自动用ItemName来填充下拉列表,不需要修改其他代码。

方案二:自定义SuggestionAdapter的getView()方法(更灵活)

如果不想修改DropdownVal类,你可以在SuggestionAdapter里重写getView()方法,手动设置显示的文本:

class SuggestionAdapter extends ArrayAdapter<DropdownVal> {
    protected static final String TAG = "SuggestionAdapter";
    private List<DropdownVal> suggestions;

    public SuggestionAdapter(Activity context, String nameFilter) {
        super(context, android.R.layout.simple_dropdown_item_1line);
        suggestions = new ArrayList<DropdownVal>();
    }

    // 其他已有方法...

    // 添加这个getView方法
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 复用布局,提升性能
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext())
                    .inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
        }
        // 获取布局里的TextView(系统布局的id是android.R.id.text1)
        TextView textView = convertView.findViewById(android.R.id.text1);
        // 获取当前项的DropdownVal对象,设置显示文本为ItemName
        DropdownVal currentItem = getItem(position);
        textView.setText(currentItem.getItemName());
        return convertView;
    }
}

这种方法的好处是,如果你以后需要给下拉列表添加更复杂的布局(比如左侧加图标、显示更多信息),直接修改getView()里的布局和逻辑就行。

两种方案都能解决你的问题,建议先用方案一,更简洁;如果有自定义布局的需求再用方案二。

内容的提问来源于stack exchange,提问作者An08NY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:41:59