android – 获取LinearLayout Gravity

我需要获得LinearLayout的重力值.我检查了文档,我只找到了如何设置它(setGravity(value)).任何人都知道是否有办法获得LinearLayout引力?

谢谢

我自己没有尝试过,但从逻辑上讲,它应该可行.

问题是变量mGravity(保存LinearLayout的当前重力信息)是私有的.并且没有访问器方法可供您访问它.

解决此问题的一种方法是使用Reflection API.

另一种(更清洁)方式是扩展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()将获得重力信息.

相关文章
相关标签/搜索