Android gridview onItemClickListener设置活动背景图片

时间:2016-12-29 22:40:40

标签: android android-gridview android-application-class

我几乎坚持使用我的Android应用程序...我正在尝试使用图像进行gridview

enter image description here

并使用OnItemClickListener()将图像设置为背景。  我遇到的问题......当我将图像设置为背景时,它会在活动关闭时消失。

我希望用户通过从gridview中选择来设置背景图像,而不会在用户退出活动时消失。

////////////我的代码///////////////////

public class ImageAdapter extends BaseAdapter {
private Context mContext;

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

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

public Object getItem(int position) {
    return null;
}

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

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {
        // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(120, 120));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

// references to our images

private Integer[] mThumbIds = { R.drawable.bg, R.drawable.bg_010,
        R.drawable.bg_003, R.drawable.bg_007, R.drawable.bg_001,
        R.drawable.bg_006, R.drawable.bg_002, R.drawable.bg_011,
        R.drawable.bg_004, R.drawable.bg_008, R.drawable.bg_005,
        R.drawable.bg_009

};
}

//////活动........... /////////

       gridview = (GridView) findViewById(R.id.grid_skin_view);
    gridview.setAdapter(new ImageAdapter(this));

    ly = (RelativeLayout) findViewById(R.id.rev_ly);

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            ly.setBackgroundResource(R.drawable.bg_003);

            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            SharedPreferences.Editor edit = settings.edit();

            int bgDrawableUri = position;
            edit.putInt("bg_drawable_uri", bgDrawableUri);
            edit.commit();

        }
    });`
}

}

1 个答案:

答案 0 :(得分:0)

查看SharedPreferences以存储数据。有很多关于如何使用的StackOverflow示例,例如this