以下代码存在于我的主要活动中。我想知道它们是否是一种方法,我可以使用传递到gridview.setAdapter()函数中的GridAdapter实例来调用方法。
GridAdapter负责用图像填充gridview。在单击时,我想获得它的位置以及GridAdapter中的一些数据。
// create a new GridView object
GridView gridview = this.findViewById(R.id.gridView);
gridview.setAdapter(new GridAdapter(this));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
thisGridAdapter.someMethod(position); //what I want to do
Log.d("gridView", String.valueOf(position));
TextView tv = findViewById(R.id.textView);
tv.setText(String.valueOf(position));
}
});
答案 0 :(得分:1)
将其分配给变量吗?
final GridAdapter adapter = new GridAdapter(this);
GridView gridView = findViewById(R.id.gridView);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
adapter.someMethod(position);
}
});
或者,使用GridView#getAdapter()
方法并将其强制转换为适配器类:
final GridView gridView = findViewById(R.id.gridView);
gridView.setAdapter(new GridAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
((GridAdapter) gridView.getAdapter).someMethod(position);
}
});