作者:mobiledu2502890887 | 来源:互联网 | 2023-09-15 20:30
我们在真实项目中通常会遇到ListView或者GridView嵌套在ScrollView中问题。但是做的时候会发现,一旦两者进行嵌套,即会发生冲突。得不到我们希望的效果。由于ListView和Grid
我们在真实项目中通常会遇到ListView或者GridView嵌套在ScrollView中问题。但是做的时候会发现,一旦两者进行嵌套,即会发生冲突。得不到我们希望的效果。由于ListView和GridView本身都继承于ScrollView,一旦在ScrollView中嵌套ScrollView,那么里面的ScrollView高度计算就会出现问题。我们也就无法得到想要的效果。下面进入正题,我们将分别讨论ScrollView中嵌套ListView和FGridView的情况:
核心解决方案: 重写ListView或者GridView的OnMesure 方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
一、ScrollView中嵌套ListView
新建MyListView类,继承ListView,并重写onMeasure()方法
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) {
// TODO Auto-generated method stub
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
二、ScrollView中嵌套GridView的解决方案。
新建MyGridView类,继承GridView,并重写onMeasure()方法
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;
public class MyGridView extends GridView{
public MyGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyGridView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}