gpt4 book ai didi

android - 如何在Android自定义 View 中实现滚动

转载 作者:行者123 更新时间:2023-11-29 02:12:01 25 4
gpt4 key购买 nike

我已经编写了一个自定义 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 中,但现在是 parentHeightonMeasure 中显示为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com