我在 GridView 上有一个非常基本的程序,其中包含一些按钮,如下面的代码所示。程序运行良好,按钮显示在网格中,但是当我单击时它们没有响应。如果我将代码更改为图像的网格视图,它可以正常工作。我相信我在某处gridView.setOnItemClickListener
或在某处错了public View getView()
。艾恩建议?谢谢
public class MainActivity extends Activity {
public String[] filenames ={"B1","B2","B3","B4","B5","B6"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ButtonAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent,
View v, int position, long id){
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
}
});
}
public class ButtonAdapter extends BaseAdapter {
private Context context;
public ButtonAdapter(Context c){
context = c;
}
public int getCount() {
return filenames.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
Button btn;
if (convertView == null) {
btn = new Button(context);
btn.setLayoutParams(new GridView.LayoutParams(100, 100));
btn.setPadding(8, 8, 8, 8);
}else {
btn = (Button) convertView;
}
btn.setText(filenames[position]);
btn.setTextColor(Color.WHITE);
btn.setId(position);
return btn;
}
}
}