我有一个自定义对象(MyCustomObj
)的ListView,并且我正在使用一个自定义适配器。 ListView完美显示对象列表。
我想在事件发生时更新列表中的单个项目。所以在活动中,我有:
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
错误,即使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;
}
}