从列表<string> </string>获取itemid

时间:2013-02-23 00:09:44

标签: android gridview baseadapter

我正在开发壁纸应用 我实现了这段代码,以便从资产中加载我的图片 loading-images-from-assets-folder

它工作得很好但是我从列表中获取itemid以使用id在全屏活动中显示其中一个图片或设置壁纸有问题

public long getItemId(int position) {

    return position ;
}

这是我的代码

public class ImageAdapter extends BaseAdapter{
 private Context mContext;
private List<String> list;
private AssetManager assetManager;

public ImageAdapter(Context c, List<String> list) {
    mContext = c;
   this.list = list;

}

public int getCount() {

    return list.size();
}

public Object getItem(int position) {

    return position;
}

public long getItemId(int position) {

    return position;
}

public View getView(int position, View view, ViewGroup parent) {
    ImageView imageView = new ImageView(mContext);

    try {

        InputStream is = mContext.getAssets().open(list.get(position));
        Bitmap bm = BitmapFactory.decodeStream(is);
        imageView.setImageBitmap(bm);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
    } catch (IOException e) {

        e.printStackTrace();
    }
    // TODO Auto-generated method stub
    return imageView;
}



public class Gs3Wallpaper extends Activity {
private  ImageButton Gs3Button;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    GridView gridView = (GridView) findViewById(R.id.GridView1);
    try {
        gridView.setAdapter(new ImageAdapter(this ,getImage()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    public List<String> getImage()throws IOException {
    AssetManager assetManager = getAssets();
    String[] files = assetManager.list("gallary");
    List<String> list = new ArrayList<String>();
    for (String it : files) {
        list.add("gallary"+File.separator + it);        

    }
    return list;

我不知道如何从列表中获取id我尝试使用list.get(position)但它返回的字符串不是int所以我不能将它传递给setImageResource例如

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

当您设置列表项时,您可以在HashMap getView()中设置图像或图像路径,具体取决于您的工作方式。将position用于key,将图像用作value

public class MyClass
{
    HashMap<String, Bitmap> imageMap = new HashMap<String, Bitmap>();
...

然后将其设置在getView()

public View getView(int position, View view, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);

try {

    InputStream is = mContext.getAssets().open(list.get(position));
    Bitmap bm = BitmapFactory.decodeStream(is);
    imageView.setImageBitmap(bm);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(80, 80));

    String posString = String.valueOf(position);
    imageMap.put(posString, bm);
} catch (IOException e) {
....
}

这样的事情对你有用。然后只需使用该位置即可从HashMap

中获取该位图