I have an Android GridView
with an ImageView
, TextView
and two Button\'s
. The Grid is appearing fine but I am finding it
If you want the Buttons (and anything else) to have unique click actions in your layout, you need to write a custom adapter and override getView()
:
public MyAdapter(Context context, List objects) {
...
inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
// Inflate and initialize your layout
convertView = inflater.inflate(R.layout.grid_item, parent, false);
holder = new ViewHolder();
holder.btnOne = (Button) convertView.findViewById(R.id.btnOne);
holder.btnOne.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Do something
}
});
// etc, etc...
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
// Do things that change for every grid item here, like
holder.textOne.setText(getItem(position));
return convertView;
}
class ViewHolder {
Button btnOne;
TextView textOne;
}
This concept has been explained quite well in various Google Talks over the years, here is one.
Addition
I am trying to set text of the TextView inside GridView column upon clicking on the button inside GridView.
You should be able to access any View in the layout in an onClick()
method by asking for the View's parent and then getting the ViewHolder:
public void onClick(View v) {
ViewHolder holder = (ViewHolder) ((View) v.getParent()).getTag();
// Do something with holder.textOne now
}
(This assumes that your layout does not have any nested ViewGroups, so adjust accordingly.)