以编程方式获取android:padding属性 [英] Get android:padding attribute programmatically

查看:89
本文介绍了以编程方式获取android:padding属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从视图中,如何以编程方式获取android:padding属性的值?我当前正在使用:

From a view, how can I get the value of the android:padding attribute programmatically? 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,我也尝试使用"android:padding"作为属性名称,但仍返回-1.

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

我的要求:在布局XML中指定android:padding值时,视图将使用此填充.如果未指定填充,它将使用默认填充

推荐答案

最简单的方法是使用android.R.styleable(如果已有的话).获取自定义属性所使用的方法相同.R.styleable是一个包含属性值的int数组的类.因此,您需要创建自己的int数组,其中包含所需属性的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;


}

根据@Eselfar的评论进行
不要忘记释放TypedArray: arr.recycle()

EDIT as per @Eselfar's comment:
Don't forget to release the TypedArray: arr.recycle() !

这篇关于以编程方式获取android:padding属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆