Michal Michal - 14 days ago 7
Android Question

Android: SeekBar with custom drawable

I have SeekBar with custom drawable. Progress element is not rendered from left side exactly but it is moved to right. How can I avoid this?

enter image description here

<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@android:id/summary"
android:background="@null"

android:progressDrawable="@drawable/seekbar"
android:thumb="@drawable/seekbar_thumb"/>


seekbar.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item
android:id="@android:id/background"
android:drawable="@drawable/seekbar_background"/>
<item android:id="@android:id/progress">
<clip android:drawable="@drawable/seekbar_progress" />
</item>

</layer-list>


seekbar_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line">

<stroke android:width="2dp" android:color="@color/colorNeutral" />

</shape>


seekbar_progress.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line">

<stroke
android:width="4dp"
android:color="@color/colorAccentDark" />
</shape>


EDIT:

As mentioned in comments if there will be both widths same problem disappear. But I need make it with two different widths through drawable is it possible? Maybe with different shapes not just lines?

Answer

I can not explain why this is an issue when drawing strokes, I think it has something to do with the strokes width, but I did not yet find the source to verify.

Fixing the Overlay

To remove the issue at hand, you can just set an inset on your left side. A value of 1dp or 2dp both work and the seekbar will be drawn properly.

Note: Using this approach there should be no risk that the background could be too short and not visible with low progress values, since the thumb would overlay and hide it in any case.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:drawable="@drawable/seekbar_background"
        android:left="2dp"><!-- or 1dp -->
    </item>
    <item android:id="@android:id/progress">
        <clip android:drawable="@drawable/seekbar_progress"/>
    </item>
</layer-list>