Get android:padding attribute programmatically

前端 未结 3 1579

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 = \"h         


        
3条回答
  •  醉话见心
    2021-02-07 06:39

    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;
    
    
    }
    

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

提交回复
热议问题