Android custom view inherit all styles and attributes from parent

♀尐吖头ヾ 提交于 2021-01-29 05:15:17

问题


If you create a custom view that extends a parent view, how can you inherit all styles and attributes from the parent view?

For example if I declare a SeekBar in xml and style it, everything works normally. If I extend this view with no additional methods all the default styling and formatting is gone.

Original xml. The styling here works as expected:

        <SeekBar
        android:id="@+id/seekBar"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_default"
        android:layout_marginEnd="@dimen/margin_default"
        android:thumb="@drawable/ic_custom_thumb"/>

If I extend SeekBar without adding anything, all the styling is different. For example the track color is different, and the thumb is cut off on both sides.

class CustomSeekBar : SeekBar {
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)}

And the xml:

    <com.namespace.CustomSeekBar
    android:id="@+id/seekBar"
    style="@style/Widget.AppCompat.ProgressBar.Horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="@dimen/margin_default"
    android:layout_marginEnd="@dimen/margin_default"
    android:thumb="@drawable/ic_custom_thumb"/> 

What do I need to do to make this CustomSeekBar look and function exactly like the default one? Trying to make a custom view that adds some functionality without changing the default xml styling/theming and such. Will I need to rebuild all the default styling and theming or is there a way to just inherit them?


回答1:


use parent instead of style in your Custom Seekbar:

<com.namespace.CustomSeekBar
    android:id="@+id/seekBar"
    parent="@style/Widget.AppCompat.ProgressBar.Horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="@dimen/margin_default"
    android:layout_marginEnd="@dimen/margin_default"
    android:thumb="@drawable/ic_custom_thumb"/> 


来源:https://stackoverflow.com/questions/53051920/android-custom-view-inherit-all-styles-and-attributes-from-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!