Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an ImageView in java code, within an existing Layout?

I'm looking for an easy way for the user to see how many drinks they've had for a BAC calculator.

Picture of the app:

PICTURE OF THE APP

On button press, I would like an image to be added to the screen, directly under the spinner and with left alignment. When I press the button again, I want another image to be added to the screen.

So if I pressed the add beer button, a drawable of a beer would appear below the spinner. If I pressed the add beer button again, I want there to be TWO drawables of beers under the spinner, preferably with them being added from the right.

(Also, having them reach their width limit, wrapping around, and starting again on the left, but below a full line, would be AWESOME)

I can't figure out how to do this. I assume adding a ImageView in code to a relative layout (because it needs to be positioned to the right) would be the best route, but if it's possible in xml I'd be more than happy to use that. Any help?

like image 826
Dan T Avatar asked Jun 08 '10 02:06

Dan T


People also ask

How do you set the content of an ImageView in your Java code?

ImageView imageView = new ImageView(this); imageView. setImageResource(R. drawable. beerbottle); RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.


1 Answers

In the button's click callback, create an ImageView object, set the bottle image, and position it. For example (I'm assuming the names of your elements):

ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.beerbottle);

RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.RelativeLayout01);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT,
    RelativeLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.addRule(RelativeLayout.BELOW, R.id.ButtonRecalculate);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

relativeLayout.addView(imageView, layoutParams);

I haven't tested this, mind you, but it should give you a good start. You'll probably need to add other parameters to the ImageView and possibly to the LayoutParams to make it look good, plus tracking how many bottles are displayed, etc.

like image 178
Daniel Waechter Avatar answered Sep 19 '22 22:09

Daniel Waechter