Android自定义视图从父视图继承所有样式和属性



如果创建一个扩展父视图的自定义视图,如何从父视图继承所有样式和属性?

例如,如果我用xml声明一个SeekBar并对其进行样式设置,那么一切都可以正常工作。如果我在没有其他方法的情况下扩展这个视图,那么所有默认的样式和格式都将消失。

原始xml。这里的造型如预期:

<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"/>

如果我在不添加任何内容的情况下扩展SeekBar,那么所有的样式都会有所不同。例如,轨迹颜色不同,拇指两侧被切掉。

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)}

以及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"/> 

我需要做些什么才能使这个CustomSeekBar的外观和功能与默认的完全一样?尝试创建一个自定义视图,在不更改默认xml样式/主题等的情况下添加一些功能。我需要重新构建所有默认的样式和主题吗?或者有办法继承它们吗?

在自定义搜索栏中使用父项而不是样式:

<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"/> 

最新更新