計算並設定ListView的高度,防止巢狀ScrollView監聽出現問題,(兩種方法,一種自定義,一種測量)
阿新 • • 發佈:2019-02-10
第一種自定義ListView
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
//重寫測量的方法
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height=MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2 , MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, height);
}
}
第二種,在程式碼裡面進行重新測量
public class MainActivity extends Activity {
private ListView lv;
private List<String> list;
private int hight;
private ArrayAdapter listAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
inData();
setLv();
}
private void setLv() {
//先獲取listview的介面卡
listAdapter = (ArrayAdapter) lv.getAdapter();
if(listAdapter!=null){
//設定每一條專案的高度
for (int i = 0; i < listAdapter.getCount(); i++) {
//獲取每一個條目
View item = listAdapter.getView(i, null, lv);
//建立一個新的LayoutParams,並設定寬高,賦值給item
item.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 40));
//把item重新計算item的寬高
item.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
//獲取item測量後的高度,併疊加到hight上
hight+=item.getMeasuredHeight();
}
//獲取lv的佈局引數物件
LayoutParams params = lv.getLayoutParams();
//重新設定params的高度,為每個條目的高度和,加上分隔線的高度,加上頭高,尾高,就是listview的總高度
params.height=hight+lv.getDividerHeight()*(listAdapter.getCount()-1)+lv.getPaddingTop()+lv.getPaddingBottom();
//這裡可以獲取螢幕的總高度
int h=getWindowManager().getDefaultDisplay().getHeight();
//如果params.height大於螢幕的二分之一,則設定為螢幕的二分之一
if(params.height>h/2){
params.height=h/2;
}
//重新設定lv的佈局引數
lv.setLayoutParams(params);
}
}
巢狀ScrollView監聽問題
private void inData() {
list = new ArrayList<String>();
for (int i = 0; i < 30; i++) {
list.add("這裡是item"+i);
}
lv.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, list));
//巢狀Scrollview還會出現事件分發問題,在這裡通過取消父控制元件的攔截事件進行獲取事件,然後進行處理
lv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()!=MotionEvent.ACTION_UP){
lv.getParent().requestDisallowInterceptTouchEvent(true);
}else{
lv.getParent().requestDisallowInterceptTouchEvent(false);
}
return false;
}
});
}
}