您的位置:首页 > 其它

ScrollView子View为自定义View时需要注意的几点问题

2014-12-09 11:36 495 查看
From: http://blog.csdn.net/caesardadi/article/details/8307449
在内容现实不全时,通常的做法是在布局中加入ScrollView,使其可以滚定显示。

在使用ScrollView时需要注意以下几点:

1. ScrollView要求其只有一个子View。当有多个View时,可以使用LinearLayout等布局包含,使其直接子View只有一个。

2. 当ScrollView的子View为自定义View时,

[java]
view plaincopy

<span style="font-size:14px;"> mScrollView = new ScrollView(this);
ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mScrollView.setLayoutParams(param);
mScrollView.addView((View) mMobileView);</span>

上边的代码中mMobileView 为自定义的View。此时子View的内容是不会显示的,需要通过以下两种方式的设置来显示子VIew
方法一:mScrollView.setFillViewport(true); 本方法是使子View可以拉伸来填满整个屏幕

方法二:在自定义View类中MobileView(class MobileView extends View)重写onMeasure方法

[java]
view plaincopy

<span style="font-size:14px;">protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
setMeasuredDimension(GlobalFun.BWScreenWidth, GlobalFun.BWScreenHeight);
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}</span>

调用setMeasuredDimension(GlobalFun.BWScreenWidth, GlobalFun.BWScreenHeight);来设置本View的宽和高,这样就会显示。注意宽度和高度必须大于设备的宽和高,此时才会滚动。

3.我遇到这样的情况,我自定义的View是全屏显示的,但是我又需要能够使当满足特定条件时,这个View能够指定其向上或者向下移动指定距离。这时我打算在再加一个子View实现占位的作用,从而实现宽和高为全屏的子View能够滚动。代码如下:

[java]
view plaincopy

<span style="font-size:14px;"> mScrollView = new ScrollView(this);
ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mScrollView.setLayoutParams(param);

mFillView = new FillView(this);//占位的View
// mFillView.layout(l, t, r, b);

mLinearLayoutMobileMain = new LinearLayout(this);
LinearLayout.LayoutParams param3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mLinearLayoutMobileMain.setLayoutParams(param3);
mLinearLayoutMobileMain.setOrientation(LinearLayout.VERTICAL);

mLinearLayoutMobileMain.addView((View)mMobileView);
mLinearLayoutMobileMain.addView(mFillView);

mScrollView.addView(mLinearLayoutMobileMain);</span>

由于ScrollView只能有一个子View,所以使用LinearLayout包含这两个子VIew(mFillView 和mMobileView)。
FillView中的代码

[java]
view plaincopy

<span style="font-size:14px;">public class FillView extends View {

public FillView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(GlobalFun.BWScreenWidth, GlobalFun.BWScreenHeight);
}

}
</span>

设置mFillVIew的 宽和高是屏幕的宽和高,同时自定义的mMobileView的宽和高也是屏幕的宽和高,这样就达到了目的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: