I have a very basic program on GridView with some buttons as in the code below. The program runs fine and buttons show in grid, but they do not respond when I click. If I change my code to a gridview of images, it works fine. I believe I am wrong somewhere in the gridView.setOnItemClickListener or in public View getView(). Ayn suggestion? thanks
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;
}
}
}
You need to set Buttons property focusable and clickable to false. Because focus and click event is captured by button in current case, not on grid view item. Change your code to following: