2016-08-10 71 views
3

无法从我的CustomView中获取引力属性(android:gravity)。如何在自定义视图中获取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(); throws方法找不到异常;

((LayoutParams)getLayoutParams()).gravity;回报的Android值:layout_gravity

反正我有可以从视图中的重力属性?

+2

首先你需要明白'gravity'和'layout_gravity'不是一回事。 http://stackoverflow.com/documentation/android/94/layouts/398/gravity-and-layout-gravity#t=201608101551183172231 –

+4

我知道兄弟。我认为你不清楚这个问题。我想要从我的java代码中获取XML中的重力属性的值。不是layout_gravity。我可以得到layout_gravity,但不是重力。 –

+2

@BartekLipinski我不认为他对这两者感到困惑,只是他能够得到一个,而不是另一个,并质疑为什么他不能'getGravity()' – Doomsknight

回答

2

LinearLayoutgetGravity()方法仅在API 24开始公开。This answer提出了一种使用反射在早期版本中获取它的方法。

对于只是一个普通的自定义视图,您可以访问重力属性是这样的:

声明android:gravity属性,为custom attributesDon't set the format.

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

在您的项目布局xml中设置重力。

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

在构造函数中获取重力属性。

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属性或者,你可以定义自己的gravity使用相同的标志值的属性。见this answer

相关问题