解決 ListView 不能撐開問題
方法一
動態的計算 ListView
實際高度,使其可以撐開父元素
/**
* 動態設置 ListView 高度,使其可以撐開父元素
*/
private void setListViewHeight(){
if (listAdapter == null) {
return;
}
int listViewHeight = 0;
for(int i=0; i<listAdapter.getCount(); i++){
View temp = listAdapter.getView(i,null, listView);
temp.measure(0,0);
listViewHeight += temp.getMeasuredHeight();
}
LayoutParams layoutParams = this.listView.getLayoutParams();
layoutParams.height = listViewHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(layoutParams);
listView.setFocusable(false);
}
方法二
繼承 ListView
復寫 onMeasure
方法,使其不能滾動。
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class NoScrollListview extends ListView {
public NoScrollListview(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 設置不滾動
*/
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
解決撐開 ListView
后滾動位置不正常問題
重新計算元素大小后將滾動條移到最上面有些時候并不能成功,正確的做法是在 ListView
注冊后將其焦點取消掉。
listView.setFocusable(false);