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

后端 未结 1 805
南笙
南笙 2021-02-07 04:46

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:

相关标签:
1条回答
  • 2021-02-07 04:50

    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.

    0 讨论(0)
提交回复
热议问题