[英]How to change one Button background in a gridview? — Android
I have a GridView with 16 ImageView buttons. 我有一个带有16个ImageView按钮的GridView。 My program makes a random number and when the user clicks a button in the gridview, I want it to take the random number (0-15) and set the background of the tile with the same position as the random number (0-15) to a different image. 我的程序生成一个随机数,当用户单击gridview中的按钮时,我希望它采用随机数(0-15)并将图块的背景设置为与随机数相同的位置(0-15)到不同的图像。 How can I just change one of the buttons background? 如何更改按钮背景之一? Here's my code so far: 到目前为止,这是我的代码:
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;
}
}
}
I think you want some thing like this.. 我想你想要这样的东西。
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
int randomNumber = random.nextInt(16);
ImageView imageView=(ImageView) parent.getChildAt(randomNumber);
imageView.setImageResource(R.drawable.random_bg);
}
});
You can use your GridView's getChildAt(int position) method to get the child (ImageView) at a specified index. 您可以使用GridView的getChildAt(int position)方法在指定的索引处获取子项(ImageView)。
From there, you can of course just cast the child to an ImageView and set the background. 当然,您可以从那里将孩子投射到ImageView并设置背景。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.