Android TextView 的自定义属性

3

可能是重复的问题:
如何在Android中读取自定义属性

最近我了解了自定义属性。我想向TextView添加自定义属性。

目前为止,我有:

属性文件:

<resources>
    <attr name="binding" format="string" />
    <declare-styleable name="TextView">
        <attr name="binding" />
    </declare-styleable>

布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
     xmlns:custom="http://schemas.android.com/apk/res/de.innosoft.android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

        <TextView
            custom:binding="test"/>

给定一个TextView
TextView tv = ...

我该如何获取这个属性的值(它是“test”)?我了解到了obtainStyledAttributes,但不知道如何在这里使用它。
2个回答

5
没问题,您可以像这样扩展您的文本视图。
 public class CustomTV extends TextView {

 public final String YOURATTRS;

 public CustomTV(Context context, AttributeSet attrs) {
    super(context, attrs);
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomTV);
    YOURATTRS = ta.getString(R.styleable.CustomTV_binding);
    ta.recycle();

 // use your attrs or not
 }

以及 attrs.xml 文件:

<declare-styleable name="CustomTV">
     <attr name="binding" format="string"/>
</declare-styleable>

2
我为什么总是将自定义属性设置为null? - Kostanos

3

据我所知,你有两个选项:

  • 创建一个扩展TextView的自定义视图,并具有接受AttributeSet的构造函数。然后你可以在此构造函数中获取自定义属性。请参阅此教程: 创建View类
  • 实现自己的LayoutInfalter.Factory,在其中处理自定义属性。

最好查看这个问题: 如何在Android中读取自定义属性, 它几乎相同。


非常感谢您提供另一篇文章的链接,似乎我需要它。但是我仍然不知道如何获取自定义属性值,例如对于TextView。(使用obtainStyledAttributes吗?) - cdbeelala89
@cdbeelala89,请查看我在答案中提到的教程。基本上,您需要创建一个名为MyTextView的类,它继承自TextView,并实现一个构造函数,该函数接受上下文和属性,并使用obtainStyledAttributes获取方便的TypedArray - Mikita Belahlazau
我们如何通过编程设置自定义属性值? - Mohammad Afrashteh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接