Get LinearLayout Gravity

后端 未结 3 1446
一整个雨季
一整个雨季 2020-12-21 07:13

I was needing to get the value of the gravity of a LinearLayout. I checked the documentation and I only found how to set it ( setGravity(value) ).

相关标签:
3条回答
  • 2020-12-21 07:26

    API >= 24

    getGravity ()

    https://developer.android.com/reference/android/widget/LinearLayout.html#getGravity()

    API < 24

    using reflection:

    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) {}
    
    0 讨论(0)
  • 2020-12-21 07:29

    I haven't tried this myself, but logically, it should work.

    The problem is that the variable mGravity(that holds the current gravity info for the LinearLayout) is private. And no accessor methods exist to provide you access to it.

    One way of solving this would be by using Reflection API.

    Another (and much much cleaner) way would be to extend LinearLayout and override setGravity(int). For instance, like this:

    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;
        }
    }
    

    As you can tell, calling getGravityVal() on the custom LinearLayout will get you the gravity info.

    0 讨论(0)
  • 2020-12-21 07:31

    You should get it from the LayoutParams of the LinearLayout:

    mLinearLayout.getLayoutParams().gravity
    

    @see doc of LinearLayout.LayoutParams:

    public int  gravity Gravity for the view associated with these LayoutParams.
    
    0 讨论(0)
提交回复
热议问题