无法获取重力属性(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();
抛出方法未找到异常;
((LayoutParams)getLayoutParams()).gravity;
返回 android:layout_gravity 的值
无论如何我可以从视图中获取重力属性吗?
The getGravity()
的方法LinearLayout
仅从 API 24 开始公开。这个答案 https://stackoverflow.com/a/38605915/3681880建议在早期版本中使用反射来获取它。
对于普通的自定义视图,您可以像这样访问重力属性:
声明android:gravity
属性在你的自定义属性 https://developer.android.com/training/custom-views/create-view.html. 不要设置格式。 https://stackoverflow.com/a/27050778/3681880
<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
使用相同标志值的属性。看这个答案 https://stackoverflow.com/a/39676977/3681880.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)