作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经编写了一个自定义 View ,我想确保它在任何屏幕尺寸上都可见。
我已经覆盖了 onMeasure:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth, parentHeight);
}
当 View 小于屏幕时,这似乎工作正常。不过,有时自定义 View 比屏幕大,而我打算使用较小的屏幕尺寸,所以我将自定义 View 包装在 ScrollView
中,但现在是 parentHeight
在 onMeasure
中显示为 0。
我已经将自定义 View 的父类(super class)从 View
更改为 ScrollView
,希望能够轻松继承滚动功能,但这并没有发生,所以我只能尝试找到一种方法来使 ScrollView
功能与我的自定义 View 一起使用,或者编写我自己的滚动功能。
有人有什么建议吗?我看过this post on Large Image Scrolling Using Low Level Touch Events如果我被迫编写自己的功能,我打算复制其中的一些功能,但无论哪种方式,我都希望能向正确的方向插入。
最佳答案
原来答案很简单。我保留了 ScrollView
并更改了我的 onMeasure。需要注意的是,尽管 Android 会提供宽度,但不会提供高度,这最初让我感到困惑。为了让 View 填充可用空间,我捕获了父 View 的可见矩形。完整代码(希望它能帮助遇到同样问题的其他人):
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight;
if(isLandscape()) {
Rect r = new Rect();
((ScrollView)getParent()).getGlobalVisibleRect(r);
parentHeight = r.bottom - r.top;
} else {
parentHeight = (int) Util.getViewHeight();
}
this.setMeasuredDimension(parentWidth, parentHeight);
}
关于android - 如何在Android自定义 View 中实现滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6758740/
我是一名优秀的程序员,十分优秀!