其他分享
首页 > 其他分享> > android – 如何在自定义视图中获取GetGravity()?

android – 如何在自定义视图中获取GetGravity()?

作者:互联网

无法从我的CustomView获取重力属性(android:gravity).

XML

<MyCustomView
 ...
 android:gravity="right"
 />

我的自定义视图;

class MyCustomView extends LinearLayout{
 ...
 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    getGravity(); //Throws method not found exception
    ((LayoutParams)getLayoutParams()).gravity; //This returns the value of android:layout_gravity
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }
 ...
}

getGravity();抛出方法未找到异常;

((的LayoutParams)getLayoutParams())的重力.返回android:layout_gravity的值

无论如何我可以从视图中获取引力属性吗?

解决方法:

LinearLayout的getGravity()方法仅从API 24开始公开.This answer提出了一种通过使用反射在早期版本中获取它的方法.

对于普通的自定义视图,您可以像这样访问gravity属性:

custom attributes. Don’t set the format.中声明android:gravity属性

<resources>
    <declare-styleable name="CustomView">
        <attr name="android:gravity" />
    </declare-styleable>
</resources>

在项目布局xml中设置重力.

<com.example.myproject.CustomView
    ...
    android:gravity="bottom" />

在构造函数中获取gravity属性.

public class CustomView extends View {

    private int mGravity = Gravity.START | Gravity.TOP;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs, R.styleable.CustomView, 0, 0);

        try {
            mGravity = a.getInteger(R.styleable.CustomView_android_gravity, Gravity.TOP);
        } finally {
            a.recycle();
        }
    }

    public int getGravity() {
        return mGravity;
    }

    public void setGravity(int gravity) {
        if (mGravity != gravity) {
            mGravity = gravity;
            invalidate();    
        }
    }
}

或者,不使用android:gravity属性,您可以定义自己的自定义重力属性,使用相同的标志值.见this answer.

标签:android,custom-view
来源: https://codeday.me/bug/20190519/1134667.html