如何确定LinearLayout是否太小而无法包含其子项

时间:2017-01-18 08:28:54

标签: android android-linearlayout android-viewgroup

LinearLayout的高度设置为wrap_content且其子级的组合高度大于屏幕时,某些孩子将无法看到。在这种情况下,我想删除孩子,直到所有孩子都可见。有效的方法是什么?

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //when measuring with unspecified, the layout will be as large as it wants to be
    super.onMeasure(UNSPECIFIED_SPEC, UNSPECIFIED_SPEC);
    if (getOrientation() == VERTICAL){
        wantedLength = getMeasuredHeight();

    } else {
        wantedLength = getMeasuredWidth();
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (getOrientation() == VERTICAL){
        measuredLength = getMeasuredHeight();

    } else {
        measuredLength = getMeasuredWidth();
    }


    while (measuredLength < wantedLength){
        //todo remove child
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getOrientation() == VERTICAL){
            measuredLength = getMeasuredHeight();

        } else {
            measuredLength = getMeasuredWidth();
        }
    }

}

有没有办法知道布局是否太小而没有测量两次?我在文档中找到MEASURED_STATE_TOO_SMALL但不知道如何使用它。 https://developer.android.com/reference/android/view/View.html#getMeasuredHeightAndState()

1 个答案:

答案 0 :(得分:0)

以像素为单位获取显示尺寸

public Map<String, Integer> deriveMetrics(Activity activity) {
    try {
        DisplayMetrics metrics = new DisplayMetrics();

        if (activity != null) {
            activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        }

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("screenWidth", Integer.valueOf(metrics.widthPixels));
        map.put("screenHeight", Integer.valueOf(metrics.heightPixels));
        map.put("screenDensity", Integer.valueOf(metrics.densityDpi));

        return map;
    } catch (Exception err) {
        ; // just use zero values
        return null;
    }
}
  

然后您可以通过调用viewName.getParent()和来获取父视图   使用getWidth()和getHeight()可以获得所需的像素。

     

然后计算要保留哪一个以及要删除哪一个。