我有ListView
假设SquirrelAdapter
。像这样:
public class SquirrelAdapter extends ArrayAdapter<Squirrel> {
private LayoutInflater layoutInflater;
private Context context;
private int resource;
public SquirrelAdapter (Context context, int resource, List<Squirrel> squirrels) {
super(context, resource, squirrels);
layoutInflater = LayoutInflater.from(context);
this.context = context;
this.resource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Squirrel squirrel = getItem( position );
convertView = layoutInflater.inflate(resource, null);
TextView squirrelNicknameTextView = (TextView) convertView.findViewById(R.id.squirrelNickname);
squirrelNicknameTextView.setText( squirrel.getCuteNickname() );
return convertView;
}
}
所以在activity
我可以这样做:
Squirrel[] squirrels = // Lot of Squirrels
SquirrelAdapter squirrelAdapter = new SquirrelAdapter(
getApplicationContext(),
R.layout.squirrel_layout,
Arrays.asList( squirrels )
);
squirrelListView.setAdapter( squirrelAdapter );
所以我可以添加onItemClickListener
:
squirrelListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bad people cast a squirrel :|
Squirrel squirrel = (Squirrel) parent.getItemAtPosition(position);
Log.i("WWF", "Tapped squirrel " + squirrel.getCuteNickname());
}
});
效果很好。但现在真是无聊的问题:
如何在AdapterView<T extends Adapter>.setOnItemClickListener
中使用Java的参数化类型?我在想下面的内容,但它会出错:
squirrelListView.setOnItemClickListener(new AdapterView<SquirrelAdapter>.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<SquirrelAdapter> parent, View view, int position, long id) {
// Squirrels approved!
Squirrel squirrel = parent.getItemAtPosition(position);
Log.i("WWF", "Tapped squirrel " + squirrel.getCuteNickname());
}
});
为什么我不能使用“
AdapterView<ArrayAdapter<T>>.OnItemClickListener
”之类的语法?为什么不存在这样的事情:
<T> getItemPosition(int position)
?可以实施吗?
感谢帮助我的松鼠不被投入。
(更严重的是,我想更多地了解这个Java功能...)
答案 0 :(得分:1)
正如您可能已经看到的那样,new AdapterView<SquirrelAdapter>.OnItemClickListener()
编译器会说,
The member type AdapterView<SquirrelAdapter>.OnItemClickListener cannot be qualified with a parameterized type, since it is static.
您在listView.setOnItemClickListener
内所做的是为Anonymous
内的interface OnItemClickListener
创建一个abstract class AdapterView
课程。现在,要在interface
类中引用abstract
,您只需要静态访问,例如AdapterView.OnItemClickListener
,因此编译错误如上所述。
即使您尝试创建implements
OnItemClickListener
只需要静态访问的具体类,例如class MyImpl implements MyAbstract.MyInterface
如果您注意到AdapterView
类
abstract class AdapterView<T extends Adapter>
表示AdapterView
可以将Adapter
或其任何子类型作为其参数。但是为了得到与Adapter
相关联的元素(数据),AdapterView
使用
Object getItem(int position);
正如你在里面看到的那样:
public Object getItemAtPosition(int position) {
T adapter = getAdapter();
return (adapter == null || position < 0) ? null : adapter.getItem(position);
}
需要在Squirrel
内投射onItemClick
。看看它是否有帮助!