首页 > 解决方案 > 自定义对象的 ListView 上的类型不兼容错误

问题描述

我有一个自定义对象 ( MyCustomObj) 的 ListView,并且我正在使用自定义适配器。ListView 完美地显示了对象列表。

我想在事件发生时更新列表中的单个项目。所以在活动中,我有:

private ListView parentLayout;
MyCustomObj customObj;

然后我试图传递一个索引i来访问要更新的特定项目,如下所示:

customObj = parentLayout.getAdapter().getItem(i);

但这会产生错误incompatible types. Required: MyCustomObj, Found: java.lang.Object

所以我将对象初始化更改为:

Object customObj

错误消失了,但对象实际上似乎是 a MyCustomObj,因为当我输出customObject到控制台时,输出是com.myapp.MyCustomObj@12ab34cd.

但在 Android Studio 中,此对象上的 setter/getter 不可用,因为它是 anObject而不是MyCustomObj.

例如,如果我想更改 id 属性,通常我会这样做:

customObj.setId(123); 但这会导致cannot resolve错误,即使setId是课堂上的适当设置器MyCustomObj

访问单个对象并更新它的正确方法是什么,为什么控制台显示自定义对象?(我知道更新对象后我需要执行notifyDataSetChanged()

适配器看起来像这样:

public class MyCustomManager extends ArrayAdapter<MyCustomObj> {
    public MyCustomManager(Context context, ArrayList<MyCustomObj> customObjects) {
        super(context, 0, customObjects);
    }

    @Override
    public View getView(int position, View customView, ViewGroup parent) {
        // Get the data item for this position
        MyCustomObj customObj = getItem(position);

        // Check if an existing view is being reused, otherwise inflate the view
        if (customView == null) {
            customView = LayoutInflater.from(getContext()).inflate(R.layout.template_my_custom_view, parent, false);
        }

        // Sets the tag
        customView.setTag(customObj.getId());

        //other view stuff goes here

        // Return the completed view to render on screen
        return customView;
    }
}

标签: javaandroidandroid-listview

解决方案


尝试将对象转换为MyCustomObj

MyCustomObj  customObj = (MyCustomObj) parentLayout.getAdapter().getItem(i);

推荐阅读