0

我有一个带有 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;
        }

    }

}
4

2 回答 2

1

我想你想要这样的东西..

 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);

            }
        });
于 2012-07-10T03:55:23.573 回答
0

您可以使用 GridView 的getChildAt(int position)方法在指定索引处获取子 (ImageView)。

从那里,您当然可以将孩子投射到 ImageView 并设置背景。

于 2012-07-10T03:32:54.023 回答