How to change one Button background in a gridview? -- Android

Posted by Tstop Studios on Stack Overflow See other posts from Stack Overflow or by Tstop Studios
Published on 2012-07-10T02:50:01Z Indexed on 2012/07/10 3:15 UTC
Read the original article Hit count: 397

Filed under:
|
|

I have a GridView with 16 ImageView buttons. 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. 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;
    }

}

}

© Stack Overflow or respective owner

Related posts about android

Related posts about gridview