其他分享
首页 > 其他分享> > 覆盖onMeasure时不显示自定义LinearLayout的膨胀子级

覆盖onMeasure时不显示自定义LinearLayout的膨胀子级

作者:互联网

我正在尝试显示扩展LinearLayout的MyCustomLinearLayout.我用android:layout_height =“ match_parent”属性来夸大MyCustomLinearLayout.
我想要在此MyCustomLinearLayout中显示一个ImageView.此ImageView的高度应为match_parent,并且宽度应等于高度.我试图通过重写onMeasure()方法来实现这一点.发生的是,MyCustomLinearLayout确实像应该的那样变成了正方形,但是ImageView没有显示.

下面是我使用的代码.请注意,这是我的问题的极其简化的版本. ImageView将由更复杂的组件代替.

public MyCustomLinearLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

private void init(Context context) {
    final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.view_myimageview, this);

    setBackgroundColor(getResources().getColor(R.color.blue));
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    setMeasuredDimension(height, height);
}

view_myimageview.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <ImageView
        android:id="@+id/view_myimageview_imageview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</merge>

因此,当我重写onMeasure()方法时,没有显示ImageView;当我不重写onMeasure()方法时,则显示了ImageView,但是它太小了,因为MyCustomLinearLayout的宽度太小了.

解决方法:

这不是您重写onMeasure方法的方法,尤其是默认SDK布局的方法.现在,使用您的代码,您就使MyCustomLinearLayout正方形分配了一定的值.但是,您没有测量其子级,因此它们没有大小,并且不会出现在屏幕上.

我不确定这是否可以,但是请尝试以下操作:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int size = getMeasuredHeight();
    super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY));
}

当然,这基本上将完成onMeasure的工作两次,但是ImageView现在应该可以看到它的父级了.还有其他解决方案,但是您的问题在细节上有点稀缺.

标签:android,custom-controls
来源: https://codeday.me/bug/20191013/1910179.html