从gridview获取图像信息的可靠方法?

时间:2014-02-27 17:09:32

标签: java android gridview

基本上,我需要一种在gridview中获取图像的id / name / some的方法,以便了解用户点击的内容。

这是imageadapter的代码,我从另一个教程得到了:

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    // Keep all Images in array
    public Integer[] mThumbIds = { R.drawable.image1, R.drawable.image2,
            R.drawable.image3, R.drawable.image4, R.drawable.image5,
            R.drawable.image6, };

    // Constructor
    public ImageAdapter(Context c) {
        mContext = c;
    }

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

    @Override
    public Object getItem(int position) {
        return mThumbIds[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(mContext);
        imageView.setImageResource(mThumbIds[position]);
        imageView.setId(mThumbIds[position]);
        imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
        return imageView;
    }

}

这一切都正常,并将id设置为R.value的整数。 在我的onCreate方法中,我有:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridView gridView = (GridView) findViewById(R.id.gridView1);

        // Instance of ImageAdapter Class
        gridView.setAdapter(new ImageAdapter(this));
        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {

                String name = getStringId(v.getId()); //this is a method of else ifs that just gets a string name based on the int id.

                Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();


            }
        });
    }

这一切都很好。我遇到的问题是,R.values全都改变了!这意味着原始的int id不再指向正确的图像,基本上你不能用它做任何事情。所以我的问题是,是否有更可靠的方法来设置图像的ID?所以当我添加一些新的drawable时,它并没有完全弄乱一切?

1 个答案:

答案 0 :(得分:0)

你应该使用:

AdapterView<?> .getItemAtPosition(int position)

例如

   Integer imageId = (Integer) parent.getItemAtPosition(position);

修改

 gridView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            Integer imageId = (Integer) parent.getItemAtPosition(int position);
            if (imageId != null) {
                   // process your imageID
             }
            String name = getStringId(v.getId()); //this is a method of else ifs that just gets a string name based on the int id.

            Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();


        }
    });