How do I get the selected item from a Gridview with ImageAdapter? (Android)

六月ゝ 毕业季﹏ 提交于 2019-11-29 13:41:28

gridView.getItemAtPosition(position) calls the adapter's getItem(int position) under the scene - so implement getItem in your ImageAdapter class to return sth that will allow you to identify what is selected (maybe mobileValues[position] is enough or just what you write into textview: mobileValues[position] + "\n" + mobileValuesD[position]).

On the other hand side in onItemClick(AdapterView<?> parent, View v, int position, long id) you have allready have the position of selected item maybe it is enough information? what you are about to do in that listener?

I have put some changes to your adapter:

public class ImageAdapter extends BaseAdapter {

    private final String[] mobileValues;
    private final String[] mobileValuesD;

    public ImageAdapter(String[] mobileValues, String[] mobileValuesD) {
        this.mobileValues = mobileValues;
        this.mobileValuesD = mobileValuesD;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        if (view == null) {
            view = ViewGroup.inflate(
                    parent.getContext(), R.layout.pesquisa_2, null);
        }

        ((TextView) view.findViewById(R.id.grid_item_label))
                .setText(getItem(position));

        ((ImageView) view.findViewById(R.id.grid_item_image))
                .setImageResource(getImageResForPosition(position));

        return view;
    }

    private int getImageResForPosition(int position) {
        String mobile = mobileValues[position];
        if (mobile.equals("pdt1")) {
            return R.drawable.img1;
        } else if (mobile.equals("prd2")) {
            return R.drawable.feijao;
        } else {
            return R.drawable.acucar;
        }
    }

    @Override
    public int getCount() {
        return mobileValues.length;
    }

    @Override
    public Object getItem(int position) {
        return mobileValues[position] + "\n" + mobileValuesD[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!