天天看點

android scrollview 設定高度自适應,【Android】相容Scrollview的可動态設定高度Listview...

常用 Scrollview嵌套Listview寫法如下:

public class NoScrollListView extends ListView {

public NoScrollListView(Context context) {

super(context);

}

public NoScrollListView(Context context, AttributeSet attrs) {

super(context, attrs);

}

public NoScrollListView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

}

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);

super.onMeasure(widthMeasureSpec, expandSpec);

}

}

現在有一個需求,是要在Scrollview嵌套之下的Listview,可折疊item數目(預設顯示2個item,展開顯示全部),固不可采用上面的高度寫死方法,采用如下寫法:

public class ScrollDisabledListView extends ListView {

private int mPosition;

public ScrollDisabledListView(Context context) {

super(context);

}

public ScrollDisabledListView(Context context, AttributeSet attrs) {

super(context, attrs);

}

public ScrollDisabledListView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

}

@Override

public boolean dispatchTouchEvent(MotionEvent ev) {

final int actionMasked = ev.getActionMasked() & MotionEvent.ACTION_MASK;

if (actionMasked == MotionEvent.ACTION_DOWN) {

// 記錄手指按下時的item

mPosition = pointToPosition((int) ev.getX(), (int) ev.getY());

return super.dispatchTouchEvent(ev);

}

if (actionMasked == MotionEvent.ACTION_MOVE) {

// 最關鍵的地方,忽略MOVE 事件

// ListView onTouch擷取不到MOVE事件是以不會發生滾動處理

return true;

}

// 手指擡起時

if (actionMasked == MotionEvent.ACTION_UP

|| actionMasked == MotionEvent.ACTION_CANCEL) {

// 手指按下與擡起都在同一個視圖内,交給父控件處理,這是一個點選事件

if (pointToPosition((int) ev.getX(), (int) ev.getY()) == mPosition) {

super.dispatchTouchEvent(ev);

} else {

// 如果手指已經移出按下時的Item,說明是滾動行為,清理Item pressed狀态

setPressed(false);

invalidate();

return true;

}

}

return super.dispatchTouchEvent(ev);

}

}

另外,給出折疊listview寫法:

private void changeHisListViewHeight(boolean isExpand) {

int itemNum;

if(isExpand || mCommunityData.size() < 2) {//小于兩個情況下不折疊

itemNum = mAdapter.getCount();

} else {

itemNum = 2;

}

View listItem = mAdapter.getView(0, null, historyList);

listItem.measure(0, 0);

int itemHeight = listItem.getMeasuredHeight();

int totalHeight = itemHeight * (itemNum);

totalHeight += (historyList.getDividerHeight() * (itemNum - 1))

+ historyList.getPaddingTop() + historyList.getPaddingBottom();

ViewGroup.LayoutParams params = historyList.getLayoutParams();

params.height = totalHeight;

historyList.setLayoutParams(params);

mAdapter.notifyDataSetChanged();

}