我需要获取 LinearLayout
的重力值。我查看了文档,只找到如何设置重力值 (setGravity(value)
)。请问是否有一种方法可以获取 LinearLayout
的重力值?
谢谢。
我需要获取 LinearLayout
的重力值。我查看了文档,只找到如何设置重力值 (setGravity(value)
)。请问是否有一种方法可以获取 LinearLayout
的重力值?
谢谢。
public class LinearLayoutExposed extends LinearLayout {
// Our own gravity!
private int mGravityHolder = Gravity.START | Gravity.TOP;
public GravLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setGravity(int gravity) {
if (mGravityHolder != gravity) {
// We don't want to make changes to `gravity`
int localGravity = gravity;
// Borrowed from LinearLayout (AOSP)
if ((localGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
localGravity |= Gravity.START;
}
if ((localGravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
localGravity |= Gravity.TOP;
}
mGravityHolder = localGravity;
}
super.setGravity(gravity);
}
// And now, we have an accessor
public int getGravityVal() {
return mGravityHolder;
}
}
您可以看出,在自定义 LinearLayout
上调用 getGravityVal()
将获得重力信息。
getGravity ()
https://developer.android.com/reference/android/widget/LinearLayout.html#getGravity()
使用反射:
int gravity = -1;
try {
final Field staticField = LinearLayout.class.getDeclaredField("mGravity");
staticField.setAccessible(true);
gravity = staticField.getInt(linearLayout);
//Log.i("onFinishInflate", gravity+"");
}
catch (NoSuchFieldException e) {}
catch (IllegalArgumentException e) {}
catch (IllegalAccessException e) {}
mLinearLayout.getLayoutParams().gravity
请参阅LinearLayout.LayoutParams的文档:
public int gravity Gravity for the view associated with these LayoutParams.