自定义对象的 ListView 上的不兼容类型错误

incompatible types error on ListView of custom objects

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

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

private ListView parentLayout;
MyCustomObj customObj;

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

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

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

所以我把对象初始化改成:

Object customObj

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

但是 setters/getters 在 Android Studio 中的这个对象上不可用,因为它是 Object 而不是 MyCustomObj

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

customObj.setId(123); 但这会导致 cannot resolve 错误,即使 setIdMyCustomObj class 中的正确 setter。

访问和更新单个对象的正确方法是什么?为什么控制台显示自定义对象? (我知道更新对象后我需要执行 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;
    }
}

尝试将对象转换为 MyCustomObj

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