当前位置: 动力学知识库 > 问答 > 编程问答 >

Android studio refuses to put views inside custom container

问题描述:

I know there is silly mistake somewhere but I can't figure out where.

I got following container's code:

public class ImagesView extends LinearLayout {

public ImagesView(Context context, AttributeSet attrs) {

super(context, attrs);

}

public ImagesView(Context context) {

super(context);

}

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int widthMode = MeasureSpec.getMode(widthMeasureSpec);

int widthSize = MeasureSpec.getSize(widthMeasureSpec);

int heightMode = MeasureSpec.getMode(heightMeasureSpec);

int heightSize = MeasureSpec.getSize(heightMeasureSpec);

float ar=(float)896/768;

this.setMeasuredDimension(widthSize, (int) (widthSize/5*(1f/ar)));

//this.setMeasuredDimension(1280,240);

}

}

Layout xml:

<?xml version="1.0" encoding="utf-8"?>

<com.rhyboo.net.test.ImagesView xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="horizontal" android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@android:color/holo_red_light">

<Button

android:text="Button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/button3"

android:layout_weight="1" />

</com.rhyboo.net.test.ImagesView>

In android studio I can see size of my container is set correctly, but if I add something into container it displays child views as zero-sized:

What am I doing wrong?

网友答案:

Your onMeasure does not call super.onMeasure... so chilren are never measured. Also when calling parents onMeasure you probably want to set mode to EXACTLY for width and/or height.

分享给朋友:
您可能感兴趣的文章:
随机阅读: