【问题标题】:Proper way override fixed size custom view正确的方法覆盖固定大小的自定义视图
【发布时间】:2014-10-05 14:10:44
【问题描述】:

我有一个黄色背景的自定义视图。我计划添加一个红色背景TextView,其宽度和高度都带有 ma​​tch_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 不遵守 ma​​tch_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 不再ma​​tch_parent了!

现在,我们可以看到黄色自定义视图的大小固定为 320x50。由于 ma​​tch_parent 属性,我希望 Red TextView 会填满整个自定义视图。

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

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

【问题讨论】:

    标签: android


    【解决方案1】:

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

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

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

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

    终于成功了:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      相关资源
      最近更新 更多