我有一个扩展LinearLayout
的课程 - 它几乎相同,只是略有不同。
public class CustomLinearLayout extends LinearLayout {
<Standard constructors...>
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
<Custom measuring code here>
}
}
这一切都很好,但现在没有一个孩子在Android Studio的布局编辑器属性中显示任何LinearLayout的LayoutParams属性,甚至像layout:width
那样。
我的猜测是LayoutParams不是继承的,所以我只是复制LinearLayout.LayoutParams
并在任何地方添加它,即:
public class CustomLinearLayout extends LinearLayout {
public static class LayoutParams extends LinearLayout.LayoutParams {
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(int width, int height, float weight) {
super(width, height, weight);
}
public LayoutParams(ViewGroup.LayoutParams p) {
super(p);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(LinearLayout.LayoutParams source) {
super(source);
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
而且,在attrs.xml中:
<declare-styleable name="com.domain.package.CustomLinearLayout_Layout">
<attr name="layout_width" format="dimension">
<enum name="fill_parent" value="-1" />
<enum name="match_parent" value="-1" />
<enum name="wrap_content" value="-2" />
</attr>
</declare-styleable>
以下是布局中的视图:
<?xml version="1.0" encoding="utf-8"?>
<com.domain.package.CustomLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
主要是作为测试,看看是否有效。但是,编辑器中没有任何内容。我编译了项目,并尝试了declare-styleable
有没有完整的包名称。我错过了什么?
(编辑:只是为了澄清最终目标 - 我想在Android Studio编辑器中看到LinearLayout.LayoutParams
&#39;属性。我一直希望它们能够自动继承,但自那以后#39 ;不是这样,我试图通过继承LinearLayout.LayoutParams
来复制它们,但这也不起作用。如果还有继承LinearLayout
的方法&# 39; s样式,这将是首选。)