Note that there are some explanatory texts on larger screens.

plurals
  1. POPass drawable image to TypedArray in Android
    primarykey
    data
    text
    <p>I am trying to implement a segmentated radio button from here: <a href="https://github.com/makeramen/android-segmentedradiobutton" rel="nofollow">https://github.com/makeramen/android-segmentedradiobutton</a> but I need to set the image programmatically and not in XML.</p> <p>This is the source of the custom RadioButton:</p> <pre><code>public class CenteredImageButton extends RadioButton { Drawable image; public CenteredImageButton(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CompoundButton, 0, 0); image = a.getDrawable(1); setButtonDrawable(android.R.id.empty); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (image != null) { image.setState(getDrawableState()); // scale image to fit inside button int imgHeight = image.getIntrinsicHeight(); Log.d("IMAGEHEIGHT", "imageWidth is " + imgHeight); int imgWidth = image.getIntrinsicWidth(); Log.d("IMAGEWIDTH", "imageWidth is " + imgWidth); int btnWidth = getWidth(); Log.d("BUTTONWIDTH", "buttonWidth is " + btnWidth); int btnHeight = getHeight(); Log.d("BUTTONHEIGHT", "buttonHeight is " + btnHeight); float scale; if (imgWidth &lt;= btnWidth &amp;&amp; imgHeight &lt;= btnHeight) { scale = 1.0f; } else { scale = Math.min((float) btnWidth / (float) imgWidth, (float) btnHeight / (float) imgHeight); } Log.d("SCALE", "scale is " + scale); int dx = (int) ((btnWidth - imgWidth * scale) * 0.5f + 0.5f); Log.d("DX", "dx is " + dx); int dy = (int) ((btnHeight - imgHeight * scale) * 0.5f + 0.5f); Log.d("DY", "dy is " + dy); image.setBounds(dx, dy, (int) (dx + imgWidth * scale), (int) (dy + imgHeight * scale)); image.draw(canvas); } } </code></pre> <p>I am setting the drawable in another file like this:</p> <pre><code>private void setButtonImageProperties(RadioButton button,Drawable drawable){ button.setGravity(Gravity.CENTER); Resources resources = this.context.getResources(); float dipValue = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, resources.getDisplayMetrics()); float dipValue1 = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 80, resources.getDisplayMetrics()); button.setMinHeight((int) dipValue); button.setMinWidth((int) dipValue1); button.setButtonDrawable(drawable); } </code></pre> <p>Please anyone, advise. I really need helping hand. Thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload