我在文件layers.xml中有一个图层列表:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/outer_rect">
<shape android:shape="rectangle">
<stroke
android:width="3dp"
android:color="@color/gray4"/>
<solid android:color="@color/white"/>
</shape>
</item>
<item android:top="10dp" android:bottom="10dp" android:left="10dp" android:right="10dp"
android:drawable="@drawable/dot_pattern_bitmap"/>
</layer-list>
这在自定义的 FrameLayout customView.xml 中使用:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/layers"/>
</merge>
它本身用于例如
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/space_m"
android:orientation="vertical">
<my.namespace.customView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
此外,我有 CustomView.java 类来编辑 customView(尤其是图层)的行为。
在那里,我试图根据 customView 的大小(和参数“比率”)来更新层列表的大小。我试过这样:
// ...
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
layoutWidth = MeasureSpec.getSize(widthMeasureSpec);
layoutHeight = MeasureSpec.getSize(heightMeasureSpec);
readjustSize(ratio);
}
private void readjustSize(final double ratio) {
if (layoutHeight != 0 && layoutWidth != 0) {
// determine desired width and height using the layout width
int desiredWidth = layoutWidth;
int desiredHeight = (int) (layoutWidth / ratio);
// if it does not fit, adjust using the layout height
if (desiredHeight > layoutHeight) {
desiredHeight = layoutHeight;
desiredWidth = (int) (layoutHeight * ratio);
}
// get the basic layer
final LayerDrawable ld =
(LayerDrawable) ContextCompat.getDrawable(getContext(), R.layers);
final GradientDrawable outerRectShape =
(GradientDrawable) ld.findDrawableByLayerId(R.id.outer_rect);
// and adapt the size
outerRectShape.setSize(desiredWidth, desiredHeight);
outerRectShape.setBounds(0, 0, desiredWidth, desiredHeight);
// redraw
invalidate();
requestLayout();
}
}
所以,这是很多代码......不幸的是,这不能正常工作。如果第一次加载框架布局,我只能看到一个非常小的矩形。
只有当我来回切换到此视图时,才会按照我的意愿应用大小:
有人有想法吗?