gpt4 book ai didi

android - 在 View 的构造函数中使用 View.getParent()

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:58 25 4
gpt4 key购买 nike

为什么这行不通?

private ScrollView findScrollParent(View v)
{

if(v==null)
{
return null;
}
else if(v instanceof ScrollView)
{
return (ScrollView) v;
}
else
{
return findScrollParent((View)v.getParent());
}
}

CustomView(Context context, AttributeSet as)
{
super(context,as);
ScrollView sv = findScrollParent(this);
}

这是我膨胀的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout android:layout_height="wrap_content"
android:layout_width="wrap_content">

<com.myapp.CustomView android:layout_height="wrap_content"
android:layout_width="wrap_content"/>

</LinearLayout>

</ScrollView>
</RelativeLayout>

我想在自定义 View 中引用 ScrollView 。我的 findScrollParent 方法找到 LinearLayout 然后返回 null。我在 View v 的构造函数中调用了这个方法,这是问题所在吗?

最佳答案

您可以在 onAttachedToWindow() 方法中安全地访问您的父级。

参见 View Life Cycle.

关于android - 在 View 的构造函数中使用 View.getParent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7099249/

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