Android - GridView toast取决于位置

时间:2017-06-01 17:55:33

标签: android gridview toast

我知道这个问题很多,但由于某种原因,我不能让我的工作,这是我活动中的网格视图;

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;

            }

        }
    });

这是我的适配器;

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;


}

我正在尝试根据点击的位置进行吐司,请帮忙吗?

1 个答案:

答案 0 :(得分:0)

您已经在onclicklistener中获得了这个职位。您只需要这段代码。

 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();

        }
    });