Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to getGravity() in custom view?

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?

like image 284
Ye Min Htut Avatar asked Aug 10 '16 15:08

Ye Min Htut


1 Answers

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.

like image 98
Suragch Avatar answered Oct 08 '22 17:10

Suragch