获取机器人:填充属性编程机器人、属性

2023-09-06 13:49:37 作者:游戏名字干净

这是一个观点,我怎么能获取Android的价值:填充属性编程?我目前使用的:

From a view, how can I get the value of the android:padding attribute programatically? I am currently using:

private static final String ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android";
private static final String ATTRIBUTE_PADDING = "padding";

public ActivityWrapperView(Context context, AttributeSet attrs) {
    super(context, attrs);
    int padding = attrs.getAttributeIntValue(ANDROID_NAMESPACE, ATTRIBUTE_PADDING, -1);
}

这将返回-1,我也尝试过使用机器人:填充作为属性名称,但-1仍会返回。

This returns -1, I have also tried using "android:padding" as the attribute name but -1 is still returned.

编辑:我的要求:当一个机器人:在布局XML中指定的填充值,认为将使用此填充。如果没有指定填充,它会使用默认的填充

推荐答案

最简单的方法是使用android.R.styleable,如果它已经可用。用同样的方法,它使用用于获取自定义属性。 R.styleable是其中包含的属性值的一个int数组类。 所以,你需要创建自己的int数组,其中包含你需要atributes的INT值。

The easiest way was to use android.R.styleable, if it had had been available. The same way it uses for getting custom attributes. R.styleable is a class which contains an int arrays of attributes values. So you need to create your own int array, which contains int values of atributes you need.

public ActivityWrapperView(Context context, AttributeSet attrs) {
    super(context, attrs);

    //check attributes you need, for example all paddings
    int [] attributes = new int [] {android.R.attr.paddingLeft, android.R.attr.paddingTop, android.R.attr.paddingBottom, android.R.attr.paddingRight}

    //then obtain typed array
    TypedArray arr = context.obtainStyledAttributes(attrs, attributes);

    //and get values you need by indexes from your array attributes defined above
    int leftPadding = arr.getDimensionPixelOffset(0, -1);
    int topPadding = arr.getDimensionPixelOffset(1, -1);

    //You can check if attribute exists (in this examle checking paddingRight)
    int paddingRight = arr.hasValue(3) ? arr.getDimensionPixelOffset(3, -1) : myDefaultPaddingRight;


}
 
精彩推荐
图片推荐