当我想使用setOnItemClickListener
时,我使用下面的
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(Tab1Fragment.getContext(null)));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
}
});
但对于以下代码,我无法像上面那样做:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.gridview1, null);
GridView listView = (GridView) view.findViewById(R.id.mainGrid1);
listView.setAdapter(new Adapter());
GridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
}
});
return view;
}
这是一个错误图片
答案 0 :(得分:2)
为什么使用类名Gridview而不是您声明为listview的gridview变量
错误代码: -
GridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
} });
而不是上面的代码将其更改为
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
} });
答案 1 :(得分:1)
而不是
GridView.setOnItemClickListener(new OnItemClickListener() {
....
} });
这样做
listView.setOnItemClickListener(new OnItemClickListener() {
....
} });
GridView是一个类,而listView是一个GridView变量,您已在代码中初始化该变量。请改用它。