horizo​​ntallistview中的固定高度未显示正确的高度

时间:2013-01-03 13:12:17

标签: android android-layout

我正在使用HorizontalListView提供的here,我正在尝试显示具有固定高度和宽度的自定义视图,如下所示:

public class MyView extends View {

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

        init();
    }

    private void init() {
        setBackgroundColor((int) (Math.random() * Integer.MAX_VALUE));
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        int h = getHeight(); // shows 255, correct height
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int w = MeasureSpec.makeMeasureSpec(425, MeasureSpec.EXACTLY);
        int h = MeasureSpec.makeMeasureSpec(255, MeasureSpec.EXACTLY);
        super.onMeasure(w, h);
    }

}

在正常MyView中显示此LinearLayout时,高度和宽度都很完美。但是,当我在HorizontalListView中显示视图时,宽度是完美的,但高度不是。见这个截图:

enter image description here

宽度为425px,这是正确的,高度仅为160px而不是255.

HorizontalListView的来源中有这种方法:

private void addAndMeasureChild(final View child, int viewPos) {
    LayoutParams params = child.getLayoutParams();
    if(params == null) {
        params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    }

    addViewInLayout(child, viewPos, params, true);
    child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
                MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
}

我是否应该在这种方法中改变一些东西,或者还有其他东西可以让它起作用?

1 个答案:

答案 0 :(得分:0)

执行int h = MeasureSpec.makeMeasureSpec(255, MeasureSpec.EXACTLY);时,该255值是PX值。如果您说XML中的高度为200 DP ,那么将根据设备调整该值。不确定所显示的屏幕是HDPI还是XHDPI(我的猜测是后者),它将成倍增加,因此你的200 DP在HDPI手机(x1.5)中变为300 PX。您可以在XML中使用PX值,也可以在values.xml中定义dimension DP值为200DP。

偏好是后者。您可以在XML中使用该维度值,并在创建View时从资源中检索该值。这意味着,如果在某些时候你想让它变大,你可以改变一个值,然后你就完成了。

修改

我看到你发现了真正的问题。在任何情况下,您仍然应该使用维度方法,它将使您的代码更清晰,它将在任何手机中工作(255只能在特定组合中看起来正确。)