How to change the android:bottom at runtime?

48 views Asked by At
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:gravity="center|bottom"
        android:bottom="5dp">
        <shape android:shape="rectangle">
            <solid android:color="#FF0000" />
            <corners android:radius="2dp" />
            <size
                android:width="10dp"
                android:height="2dp" />
        </shape>
    </item>
</layer-list>

When set the android:bottom="5dp" in the .xml,it works。But now, need to change the bottom value at runtime. With the debug , xml files was parsed to GradientDrawable. So, how to change the GradientDrawable, makes set the bottom value wokrs? thanks !!!

1

There are 1 answers

1
SpiritCrusher On BEST ANSWER

You can use setLayerInset . It accepts the layer index and 4 Offset values for each of sides .

setLayerInset(layer, leftOffset, topOffset, rightOffset, bottomOffset)

below is an example of modifying the bottom offset.

val layerDrawable = ContextCompat.getDrawable(this, R.drawable.test) as LayerDrawable
layerDrawable.setLayerInset(0,0,0,0,200)
imageView.background=layerDrawable

First argument is index of layer which you want to modify in this case there is only one layer so its 0 . Rest 4 values are in pixels So make sure you convert DP to pixel first when changing the offsets.