我有一个带有 16 个 ImageView 按钮的 GridView。我的程序生成一个随机数,当用户单击网格视图中的按钮时,我希望它采用随机数(0-15)并将图块的背景设置为与随机数相同的位置(0-15)到不同的图像。如何只更改其中一个按钮背景?到目前为止,这是我的代码:
public class ButtonHider extends Activity {
Random random = new Random();
int pos;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.button_hider);
pos = random.nextInt(15);
GridView gridview = (GridView) findViewById(R.id.gvBH);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
pos = random.nextInt(16);
if (position == pos) {
Toast.makeText(ButtonHider.this, "Found Me!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ButtonHider.this, "Try Again!!",
Toast.LENGTH_SHORT).show();
}
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return 16;
}
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(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(15, 15, 15, 15);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(R.drawable.bh_b);
return imageView;
}
}
}