I know this question is asked a lot, but for some reason I can't get mine to work, here is my gridview in my activity;
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new FoodListAdapter(this, R.layout.food_items, list);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Toast.makeText(Student.this, "POS 1", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(Student.this, "POS 2", Toast.LENGTH_SHORT).show();
break;
}
}
});
and here is my adapter;
public class FoodListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Food> foodsList;
public FoodListAdapter(Context context, int layout, ArrayList<Food> foodsList) {
this.context = context;
this.layout = layout;
this.foodsList = foodsList;
}
@Override
public int getCount() {
return foodsList.size();
}
@Override
public Object getItem(int position) {
return foodsList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
CircularImageView imageView;
TextView txtName, txtPrice;
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
holder.imageView = (CircularImageView) row.findViewById(R.id.imgFood);
row.setTag(holder);
}
else {
holder = (ViewHolder) row.getTag();
}
Food food = foodsList.get(position);
holder.txtName.setText(food.getName());
holder.txtPrice.setText(food.getPrice());
byte[] foodImage = food.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
I am trying to toast depending on position clicked, any help please?
You are already getting the position in your onclicklistener. All you need is this code.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(Student.this, position+1, Toast.LENGTH_SHORT).show();
}
});