正确的方式覆盖固定大小的自定义视图

Che*_*eng 1 android

我有黄色背景的自定义视图.我打算添加一个红色背景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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在,我希望有一个固定的宽度和高度自定义视图.我意识到,在我修复宽度和高度自定义视图后,添加的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);
    }
Run Code Online (Sandbox Code Playgroud)

我意识到添加的TextView不再是match_parent!

在此输入图像描述

现在,我们可以看到黄色自定义视图的固定大小为320x50.我希望Red TextView会因match_parent属性而填满整个自定义视图.

但事实并非如此.我相信我对自定义视图的实现onMeasure是不正确的.我可以知道解决这个问题的正确方法是什么?

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

Chi*_*ang 8

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

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

        super.onMeasure(
            MeasureSpec.makeMeasureSpec(desiredWidth, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(desiredHeight, MeasureSpec.EXACTLY));
Run Code Online (Sandbox Code Playgroud)

参考链接:自定义LinearLayout的膨胀子项在覆盖onMeasure时不显示

最后它正在工作:)