【问题标题】:Get the value of android:ellipsize attribute, in a custom view constructor在自定义视图构造函数中获取 android:ellipsize 属性的值
【发布时间】:2018-05-04 02:59:56
【问题描述】:

如何在自定义View(扩展TextView)中获取属性android:ellipsize 的值?

我尝试了这些方法,但没有奏效:

Log.d(TAG, attrs.getAttributeIntValue(ANDROID_NAMESPACE, "ellipsize", -1));
Log.d(TAG, attrs.getAttributeValue(ANDROID_NAMESPACE, "ellipsize"));
Log.d(TAG, attrs.getAttributeUnsignedIntValue(ANDROID_NAMESPACE, "ellipsize", 111));
Log.d(TAG, attrs.getAttributeListValue(ANDROID_NAMESPACE, "ellipsize", new String[] {"x", "marquee"}, -1));

注意:attrs 是 AttributeSet(构造函数参数),ANDROID_NAMESPACE 是 "http://schemas.android.com/apk/res/android"。

【问题讨论】:

    标签: android attributes textview android-custom-view marquee


    【解决方案1】:

    getAttributeValue 方法在这个例子中适用于我(Kotlin):

    import android.content.Context
    import android.util.AttributeSet
    import android.widget.TextView
    
    class Text(context: Context, attrs: AttributeSet) : TextView(context, attrs) {
        init {
            println("ellipsize: " +
                    attrs.getAttributeValue(
                            "http://schemas.android.com/apk/res/android",
                            "ellipsize"
                    )
            )
        }
    }
    

    打印出来:

    11-20 20:49:18.808 26804-26804/com.package.app I/System.out: ellipsize: 1

    对于这个视图:

    <com.package.app.Text
            android:id="@+id/test"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="start" />
    

    【讨论】:

    • 谢谢。就我而言,它返回null!我找到了差异的原因:我在样式中设置了它的值(不是直接在元素 XML 标记中)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2021-06-19
    • 2011-02-22
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多