Android自定义视图从父级继承所有样式和属性 [英] Android custom view inherit all styles and attributes from parent

查看:117
本文介绍了Android自定义视图从父级继承所有样式和属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如,如果我在xml中声明SeekBar并设置其样式,则一切正常.如果我不使用其他方法来扩展此视图,则所有默认样式和格式都将消失.

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.

原始xml.此处的样式按预期工作:

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

如果我在不添加任何内容的情况下扩展SeekBar,则所有样式都不相同.例如,轨道颜色不同,并且拇指在两侧均被切除.

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

和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样式/主题等.我是否需要重建所有默认的样式和主题,或者是否可以继承它们?

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?

推荐答案

在自定义搜索栏中使用父级代替样式:

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

这篇关于Android自定义视图从父级继承所有样式和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆