gpt4 book ai didi

android - 查看 getRootView 返回自身

转载 作者:太空狗 更新时间:2023-10-29 13:35:50 26 4
gpt4 key购买 nike

我制作了一个名为 ActionButton 的自定义按钮,我正在尝试获取对平行 View 层次结构中的另一个 View 的引用。我想过使用 findViewById(int id),但我一直收到 NullPointerExceptions,所以我尝试通过 getRootView() 获取对 RootView 的引用,然后使用 findViewById(int id) 从那里获取 View 。现在的问题是 getRootView 不是返回布局或 null,而是返回调用该方法的 ActionButton。

这是我的 ActionButton,我试图在其中获取引用:

public class ActionButton extends Button {

protected void onFinishInflate(){
super.onFinishInflate();
log(getRootView() == this) //true, what I don't understand...
ConnectionLayer connectionLayer = (ConnectionLayer) findViewById(R.id.connection_layer); //Returns null...
}
}

以及我的 layout.xml 文件的概述:

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

(much more xml elements)

<com.cae.design.reaction.ui.ActionButton
android:id="@+id/actionButton"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_gravity="center_vertical" />

</LinearLayout>

<com.cae.design.reaction.ui.ConnectionLayer
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/connection_layer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.cae.design.reaction.ui.ConnectionLayer>

</FrameLayout>

如果您能向我解释为什么 getRootView 返回 View 本身,或者可以给我一个提示,我将不胜感激,我可以如何以任何其他方式引用它。

最佳答案

如果您查看 getRootView 方法的源代码:

 public View getRootView() {
if (mAttachInfo != null) {
final View v = mAttachInfo.mRootView;
if (v != null) {
return v;
}
}

View parent = this;

while (parent.mParent != null && parent.mParent instanceof View) {
parent = (View) parent.mParent;
}

return parent;
}

您会看到,此方法返回自身的唯一情况是 View 尚未附加到 View 层次结构(并且 mAttachInfo.mRootView 不为空)并且它没有父级或父级不是一个 View 实例。最好的问候。

关于android - 查看 getRootView 返回自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10801753/

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