LayerDrawable draws drawings the same size?

Hi I am trying to draw two icons of different sizes, one of the icons is just the background type and the other icon is a symbol.

When I draw both, the symbol icon gets larger to fit the size of the background icon.

Here is my code

  drawableSelectedIcons[0] = r.getDrawable(R.drawable.background);

    drawableSelectedIcons[1] = r.getDrawable((R.drawable.symbol);

    LayerDrawable layerDrawableSelected = new LayerDrawable(drawableSelectedIcons);

      

+3


source to share


2 answers


R.drawable.symbol

- a bitmap? Then it is loaded as BitmapDrawable. It has gravity. Depending on gravity, the bitmap is positioned within acceptable boundaries. Try setting gravity to Gravity.CENTER.

You can do it like this:



BitmapDrawable bd = (BitmapDrawable) r.getDrawable((R.drawable.symbol); // be careful with this cast
db.setGravity(Gravity.CENTER)

drawableSelectedIcons[1] = bd;

      

+3


source


Given that you only have this image in your layout, this should be enough for what you want:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        android:scaleType="center"
        android:src="@drawable/symbol" />

</LinearLayout>

      



Edit: to dynamically add to layout use:

ImageView imageView = new ImageView(this);
    imageView.setBackgroundResource(R.drawable.background);
    imageView.setImageResource(R.drawable.symbol);
    imageView.setScaleType(ScaleType.CENTER);
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.CENTER;
    addContentView(imageView, params);

      

+1


source







All Articles