gpt4 book ai didi

android - 如果由 android :layout_width ="match_parent" 设置 getWidth() 返回 0

转载 作者:IT老高 更新时间:2023-10-28 23:40:40 25 4
gpt4 key购买 nike

我有一个扩展 ImageView 的名为 FractalView 的类。我的目标是使用具有整个屏幕大小的此类绘制分形。它是我的 Activity 布局文件中唯一的 View ,除了顶级 LinearLayout:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFFFF">

<com.antonc.fractal_wallpaper.FractalView
android:id="@+id/fractal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"/>
</LinearLayout>

如您所见,我对 FractalView 和 LinearLayout 的 layout_width 和 layout_height 都使用了“match_parent”。在这一点上,我假设 FractalView 的大小设置为某个值,因为它匹配它的父级,它匹配它的父级(即整个屏幕)。然后我尝试使用 getWidth() 和 getHeight() 检测 FractalView 可用的大小:

public class FractalView extends ImageView {

private Context mContext;
private Handler mHandler;

private int mScrWidth;
private int mScrHeight;

public FractalView(Context context) {
super(context);
mContext = context;
init();
}

private void init() {

mScrWidth = getWidth();
mScrHeight = getHeight();
// Breakpoint
}

@Override
protected void onDraw(Canvas canvas) {
[...]
}

}

但是当我的代码到达断点时,调试器显示 mScrWidth 和 mScrHeight 为零。我尝试使用 getMeasuredWidth() 和 getMaxWidth(),但它们也返回不正确的值。我已经阅读了几个类似问题的答案,即 this one他们都解释说 getWidth() 返回图像 after 绘制后的大小,而我真正需要的是该 View 可用区域的宽度,before 我开始画画了。

有没有办法检索这些宽度和高度值?

最佳答案

onMeasure() 之后, View 的大小才可用,尤其是当它设置为 wrap_contentfill_parent 时。

您应该在 View 代码中或在布局树观察器中访问 onMeasure() 中或之后的大小:

LinearLayout layout = (LinearLayout)findViewById(R.id.mylayout);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();

}
});

您还需要将 android:id="@+id/mylayout" 添加到您的 LinearLayout 以使第二个工作。

关于android - 如果由 android :layout_width ="match_parent" 设置 getWidth() 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14592930/

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