How to getGravity() in custom view?

瘦欲@ 提交于 2019-12-22 05:06:51

问题


Can't get gravity attribute (android:gravity) from my CustomView.

XML

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

My Custom View;

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(); throws method not found exception;

((LayoutParams)getLayoutParams()).gravity; returns the value of android:layout_gravity

Is there anyway I can get the gravity attribute from the view?


回答1:


The getGravity() method of LinearLayout was only made public starting with API 24. This answer suggests a way to get it in earlier versions by using reflection.

For just a normal custom view, you can access the gravity attribute like this:

Declare the android:gravity attribute in your custom attributes. Don't set the format.

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

Set the gravity in your project layout xml.

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

Get the gravity attribute in the constructor.

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

Or instead of using the android:gravity attribute, you could define your own custom gravity attribute that uses the same flag values. See this answer.



来源:https://stackoverflow.com/questions/38878174/how-to-getgravity-in-custom-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!