在我的自定义视图上阅读Android属性

时间:2015-10-16 05:16:35

标签: android android-layout android-custom-view

我创建了一个自定义布局类(扩展RelativeLayout)并将TextView作为布局的一部分。

我想将XML中声明的属性应用到我的TextView,无论如何我可以读取android属性(不是我的自定义属性,那部分已经被处理)。

例如在我的XML中我会有:

<my.custom.MyLayout
    android:layout_width="100dp"
    android:layout_height="20dp"
    android:text="SomeText" /> 

我想阅读text属性并将其应用于我的TextView(目前它正在应用于RelativeLayout),而不是创建我自己的属性并阅读它。

我的自定义布局是这样的:

public class MyLayout extends RelativeLayout {

    private TextView textView;
    public void MyLayout(final Context context, final AttributeSet attrs) {
        /**Read android attributes and apply it to TextView **/
        ??
    }

我目前的解决方案是创建自定义属性并阅读它们,但我觉得这不是一个好的解决方案,因为我将复制声明为TextView的每个属性。

有关我当前解决方案的更多信息。

我有一个名为myText的自定义属性,我用它来将XML中声明的文本应用到我的TextView。

在我的布局XML中:

myNameSpace:myText="SomeText"

在我的Java类中阅读:

String text= a.getString(R.styleable.MyStyleable_myText);
textView.setText(text);

我正在寻找摆脱我的自定义属性并阅读“android:”属性。

1 个答案:

答案 0 :(得分:7)

首先,我不确定是否可以为android:text视图设置RelativeLayout。如果有可能在TextView实施中执行:

final Resources.Theme theme = context.getTheme();
a = theme.obtainStyledAttributes(attrs, com.android.internal.R.styleable.TextView, defStyleAttr, defStyleRes);
text = a.getText(attr);

所以基本上它与获取自定义属性的方式相同,但具有不同的样式。

如果它不起作用,我会考虑另一种方法。我为我的一个自定义视图做了这个。由于您的自定义视图中有TextView,因此您可以使用XML创建它,然后在自定义视图中获取对该子项的引用。

<YourCustomView>
    <TextView android:text="someText"/>
<YourCustomView/>