看到这个标题,有的同学可能会说控件本身不就有那个属性吗?这还不简单?于是便去xml中去寻找该方法,结果呢?当然是碰了一鼻子灰(我当初遇到这个问题的时候也是满鼻子灰)!
好了切入正题,类似的控件还有listview等滑动控件,都是没有这个属性的。最近项目遇到类似问题,当scrollview中的内容量很少的时候,scrollview不滚动,当scrollview内容量很大的时候,要scrollview布局高度控制在屏幕高度的一半,总的来说就是,scrollview包含的内容最大不能超过屏幕的一半。
既然没有maxHeight属性,那么我们就要自定义ScrollView控件了,具体操作如下:
- public class MyScrollView extends ScrollView {
- private Context mContext;
- public <span style="font-family: Arial, Helvetica, sans-serif;">MyScrollView</span>(Context context) {
- super(context);
- init(context);
- }
- public MyScrollView(Context context, AttributeSet attrs) {
- super(context, attrs);
- init(context);
- }
- public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- init(context);
- }
- private void init(Context context) {
- mContext = context;
- }
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- try {
- //最大高度显示为屏幕内容高度的一半
- Display display = ((Activity) mContext).getWindowManager().getDefaultDisplay();
- DisplayMetrics d = new DisplayMetrics();
- display.getMetrics(d);
- //此处是关键,设置控件高度不能超过屏幕高度一半(d.heightPixels / 2)(在此替换成自己需要的高度)
- heightMeasureSpec = MeasureSpec.makeMeasureSpec(d.heightPixels / 2, MeasureSpec.AT_MOST);
- } catch (Exception e) {
- e.printStackTrace();
- }
- //重新计算控件高、宽
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- }
- }
- <com.xiafeixiao.view.widget.MyScrollView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:fillViewport="true"
- android:fadingEdge="none"
- android:overScrollMode="never"
- >
- <TextView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="测试ScrollView高度"/>
- </com.xiafeixiao.view.widget.MyScrollView>