我有一个带有黄色背景的自定义视图。我计划添加一个红色背景TextView,其宽度和高度都带有match_parent。这就是我所做的。

MainActivity.java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout mainView = (LinearLayout)this.findViewById(R.id.screen_main);
        RateAppBanner rateAppBanner = new RateAppBanner(this);
        mainView.addView(rateAppBanner);
    }
}


RateAppBanner.java

public class RateAppBanner extends LinearLayout {

    public RateAppBanner(Context context) {
        super(context);

        setOrientation(HORIZONTAL);

        LayoutInflater.from(context).inflate(R.layout.rate_app_banner, this, true);

        this.setBackgroundColor(Color.YELLOW);
    }
}


rate_app_banner.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#ffffffff"
        android:background="#ffff0000"
        android:text="Hello World" />

</LinearLayout>




现在,我希望有一个固定的宽度和高度自定义视图。我意识到,在具有固定的宽度和高度自定义视图之后,添加的TextView不遵循match_parent属性。

这是我在自定义视图上所做的更改。

RateAppBanner.java

public class RateAppBanner extends LinearLayout {
    ...

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int desiredWidth = 320;
        int desiredHeight = 50;

        desiredWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, desiredWidth, getResources().getDisplayMetrics());
        desiredHeight = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, desiredHeight, getResources().getDisplayMetrics());

        super.onMeasure(desiredWidth, desiredHeight);
        //MUST CALL THIS
        setMeasuredDimension(desiredWidth, desiredHeight);
    }


我意识到添加的TextView不再与match_parent匹配!



现在,我们可以看到“黄色”自定义视图的尺寸固定为320x50。由于match_parent属性,我预计红色TextView将填满整个自定义视图。

但是,事实并非如此。我认为自定义视图onMeasure的实现不正确。我可以知道解决此问题的正确方法是什么?

完整的源代码可以从abc.zip下载

最佳答案

经过大量的反复试验和研究工作,最终找到了答案。

您已经为布局设置了度量,但没有为子视图设置度量,因此需要将其放入onMeasure方法中,

        super.onMeasure(
            MeasureSpec.makeMeasureSpec(desiredWidth, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(desiredHeight, MeasureSpec.EXACTLY));


参考链接:Inflated children of custom LinearLayout don't show when overriding onMeasure

最后它起作用了:)

09-17 15:12
查看更多