Inflated children of custom LinearLayout don't show when overriding onMeasure

时光毁灭记忆、已成空白 提交于 2019-12-02 08:01:50

问题


I'm trying to show a MyCustomLinearLayout which extends LinearLayout. I'm inflating the MyCustomLinearLayout with the android:layout_height="match_parent" attribute. What I want is to show an ImageView in this MyCustomLinearLayout. The height of this ImageView should be match_parent, and the width should be equal to the height. I'm trying to accomplish this by overriding the onMeasure() method. What happens, is that MyCustomLinearLayout does become square like it should, but the ImageView is not showing.

Below my used code. Please note that this is an extremely simplified version of my problem. The ImageView will be replaced by a more complex component.

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);
}

The view_myimageview.xml file:

<?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>

So when I override the onMeasure() method, the ImageView is not showing, when I don't override the onMeasure() method, the ImageView shows, but way too small, because the MyCustomLinearLayout's width is too small.


回答1:


That's not how you override the onMeasure method especially of a default SDK layout. Right now with your code you just made the MyCustomLinearLayout square assigning it a certain value. But, you didn't measured its children so they are sizeless and don't appear on the screen.

I'm not sure this would work but try this:

@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));
}

Of course this will basically do the work of onMeasure twice but the ImageView should be now visible filling it's parent. There are other solutions but your question is a bit scarce on details.



来源:https://stackoverflow.com/questions/13394181/inflated-children-of-custom-linearlayout-dont-show-when-overriding-onmeasure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!