从视图对象获取属性值

时间:2019-01-03 15:03:31

标签: java android android-layout

我有一个自定义View对象,并且只能访问View。 因此,我有一个名为attribute1的属性,并使用app:attribute1="value"为我的视图设置了该属性,如何仅从我的attribute对象中获取View的值,甚至可能?我可以采取什么办法? 我搜索了几乎所有地方,但找不到任何东西。

示例:

CustomView customView = new CustomView();

我想从customView中获取属性值

2 个答案:

答案 0 :(得分:1)

XML属性在AttributeSet对象内部可用,而这些属性仅在View的构造函数内部可用。

因此,如果您无法修改自定义View类的源代码,那么您将无法完成您想要做的事情。

如果可以修改类的源代码,则可以将对属性值的引用保存在构造函数中,并为其提供getter方法。例如:

private int strokeColor;

public MyCustomView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    ...

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0);
    this.strokeColor = a.getColor(R.styleable.MyCustomView_strokeColor, defaultColor);
    ...
    a.recycle();
}

public int getStrokeColor() {
    return strokeColor;
}

答案 1 :(得分:0)

Here is official documentation how to do, exactly what you want.您所需要的只是declare-styleable,您可以在其中创建用于视图的自定义属性。然后在内部视图中,在构造函数中检索值。

相关问题