java - 自定义对象的 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;
}
}
解决方案
尝试将对象转换为MyCustomObj
MyCustomObj customObj = (MyCustomObj) parentLayout.getAdapter().getItem(i);
推荐阅读
- python - 如何为 python3 导入熊猫?
- windows - 使用PowerShell将文件从一台笔记本电脑复制到另一台笔记本电脑
- c++ - 将 char 数组转换为对象指针 - 这是 UB 吗?
- javascript - 将多个参数传递给 React 中的函数
- mysql - 在没有指定变量的情况下访问 RowDataPacket
- php - 数据透视表 Laravel 的问题
- laravel - 获取与注册相关的发票号
- python - 如何从 Telegram 上的群聊中获取消息?
- generics - Kotlin 通用约束与“任何”而不是“全部”
- webpack - webpack要求,如何传递一个字符串变量?