在下面的代码中单击按钮时没有根据Imgid的位置设置背景图像,只将图像(p1.png)的第一个设置为背景!
whynot根据Imgid的位置设置背景图片?
public class Main extends Activity{
private Gallery gallery;
private ImageView imgView;
private int[] Imgid = {
R.drawable.p1, R.drawable.p2, R.drawable.p3, R.drawable.p4
};
int position;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageResource(Imgid[0]);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
imgView.setImageResource(Imgid[position]);
}
});
Button b =(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
setback(position);
}
});
}
public void setback (int position){
WallpaperManager wallpaperManager = WallpaperManager.getInstance(Main.this);
Drawable drawable = getResources().getDrawable(Imgid[position]);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
try {
wallpaperManager.setBitmap(bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return Imgid.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(cont);
imgView.setImageResource(Imgid[position]);
imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
}
答案 0 :(得分:3)
创建一个mPosition
全局变量并初始化mPosition
变量,如
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
imgView.setImageResource(Imgid[position]);
mPosition=position;
}
});
然后使用mPosition
之类的
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
setback(mPosition);
}
});
答案 1 :(得分:-1)
您是否已获得许可
<uses-permission android:name="android.permission.SET_WALLPAPER"/>