【问题标题】:How to getGravity() in custom view?如何在自定义视图中获取重力()?
【发布时间】:2016-08-10 15:50:34
【问题描述】:

无法从我的 CustomView 获取重力属性 (android: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 method not found 异常;

((LayoutParams)getLayoutParams()).gravity;返回android:layout_gravity的值

无论如何我可以从视图中获取重力属性吗?

【问题讨论】:

  • 首先您需要了解gravity 和layout_gravity 不是一回事。 stackoverflow.com/documentation/android/94/layouts/398/…
  • 我知道兄弟。我认为你不清楚这个问题。我想从我的 java 代码中获取我在 XML 中放入的重力属性的值。不是布局重力。我可以得到 layout_gravity 但不能得到重力。
  • @BartekLipinski 我不认为他对这两个感到困惑,只是他能够得到一个,而不是另一个,并质疑他为什么不能getGravity()
  • 我不知道这是否有效,但您似乎可以在较低的 API 上尝试这样的反射,但使用来自 android 24 的 getGravity。stackoverflow.com/a/38605915/4183017
  • ok..sry... 我删除了我的答案.. 'getGravity' 的东西适用于 >24,你可以按照这里的答案来实现它stackoverflow.com/questions/26558289/get-linearlayout-gravity

标签: android custom-view


【解决方案1】:

LinearLayout 的 getGravity() 方法仅从 API 24 开始公开。This answer 建议使用反射在早期版本中获取它。

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

在custom attributes 中声明android:gravity 属性。 Don'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。

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多