对于CustomListview,match_parent不起作用

时间:2015-04-07 06:30:54

标签: android listview scrollview

<com.mil.example.CustomListView
                    android:id="@+id/villa_lv"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_below="@+id/itemImageLay"
                    android:fadingEdge="none"
                    android:scrollbars="none"/>

以下是CustomListview类。

public class CustomListView extends ListView {
private float lastMotionY;

public CustomListView(Context context) {
    super(context);
}

public CustomListView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int mode = MeasureSpec.getMode(widthMeasureSpec);
    if (mode == MeasureSpec.UNSPECIFIED) {
        int height = getLayoutParams().height;
        if (height > 0)
            setMeasuredDimension(getMeasuredWidth(), height);
    }
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    int action = event.getAction();
    float x = event.getX();
    float y = event.getY();
    float dy = y - lastMotionY;
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        lastMotionY = y;
        break;
    case MotionEvent.ACTION_MOVE:
        if (Util.canScroll(this, false, (int) dy, (int) x, (int) y)) {
            lastMotionY = y;
            return false;
        }
        break;
    }
    return super.onInterceptTouchEvent(event);
}

}

我想将高度设置为match_parent,但它只显示列表的第一项。它显示了当我给出高度时的所有项目,我在另一个滚动中使用滚动工作正常。

2 个答案:

答案 0 :(得分:0)

尝试下面的操作,将自定义适配器设置为列表视图:

    listViewResult.setAdapter(customAdapter);

    listViewResult.setVisibility(View.VISIBLE);


     int totalHeight = 0;
     int adapterCount = customAdapter.getCount();
     for (int size = 0; size < adapterCount ; size++) {
         View listItem = customAdapter.getView(size, null, listViewResult);
         listItem.measure(0,0);
         totalHeight += listItem.getMeasuredHeight();
     }
     //Change Height of ListView 
     ViewGroup.LayoutParams params = listViewResult.getLayoutParams();
     params.height = totalHeight + (listViewResult.getDividerHeight() * (adapterCount - 1));
     listViewResult.setLayoutParams(params);

答案 1 :(得分:0)

尝试使用像这样的重量

<com.mil.example.CustomListView
                    android:id="@+id/villa_lv"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:layout_below="@+id/itemImageLay"
                    android:fadingEdge="none"
                    android:scrollbars="none"/>