获取LinearLayout重力
我需要获得LinearLayout
的重力值。 我检查了文档,我只找到了如何设置它( setGravity(value)
)。 任何人都知道是否有办法获得LinearLayout
重力?
谢谢
我自己并没有尝试过,但从逻辑上来说,它应该起作用。
问题是变量mGravity
(包含LinearLayout的当前重力信息)是private
。 并且不存在访问者方法来为您提供访问权限。
解决这个问题的一种方法是使用Reflection API。
另一种(也更setGravity(int)
)的方式是扩展LinearLayout
并覆盖setGravity(int)
。 例如,像这样:
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()
将为您提供重力信息。
API> = 24
getGravity()
https://developer.android.com/reference/android/widget/LinearLayout.html#getGravity()
API <24
使用反射:
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) {}
你应该从LinearLayout的LayoutParams中获得它:
mLinearLayout.getLayoutParams().gravity
@请参阅LinearLayout.LayoutParams文档:
public int gravity Gravity for the view associated with these LayoutParams.
链接地址: http://www.djcxy.com/p/93269.html
下一篇: How to add dividers and spaces between items in RecyclerView?