gpt4 book ai didi

android - 为什么不根据位置设置背景[android]

转载 作者:行者123 更新时间:2023-11-29 21:08:06 26 4
gpt4 key购买 nike

在下面的代码中,当点击按钮时,没有根据 Imgid 的位置设置背景图片,只将图片 (p1.png) 的第一张设置为背景!

为什么不根据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;
}
}
}

最佳答案

创建一个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);
}
});

关于android - 为什么不根据位置设置背景[android],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23854922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com