我有一個假想的SquirrelAdapter
的ListView
。事情是這樣的:Android的列表視圖。 AdapterView.OnItemClickListener中的參數化類型
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功能...)