gpt4 book ai didi

android - 从自定义 View 类中的属性中按 ID 获取 View

转载 作者:搜寻专家 更新时间:2023-11-01 08:33:38 28 4
gpt4 key购买 nike

我想从他的 ID 中获取一个 View ,从 xml 中的属性。我已经尝试使用 getParent() 但它返回 null。

XML

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ntwldg="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="@drawable/background_settings"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/revealView"
android:gravity="center"
android:text="TEST"
android:background="@android:color/darker_gray"
android:visibility="invisible"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

<com.dot.networkloading.NetworkLoading
android:id="@+id/network_loading"
ntwldg:text="Youtube"
ntwldg:image="@drawable/ic_youtube"
ntwldg:imageBackground="@drawable/ic_youtube"
ntwldg:revealView="@id/revealView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

属性 revealView 引用上面的View

代码 - NetworkLoading (init())

        title = (TextView) findViewById(R.id.title);
image = (ImageView) findViewById(R.id.image);
imageBackground = (ImageView) findViewById(R.id.imageBackground);
finishView = findViewById(R.id.revealView);

String text = attributes.getString(R.styleable.network_loading_text);
imageId = attributes.getResourceId(R.styleable.network_loading_image, 0);
imageBackgroundId = attributes.getResourceId(R.styleable.network_loading_imageBackground, 0);

finishView = ((View) getParent()).findViewById(attributes.getResourceId(R.styleable.network_loading_revealView, R.id.revealView));

最佳答案

看来您过早地尝试找到您的 revealView。在构造函数中,View 尚未添加到它所在的布局中,因此 getParent() 将返回 null。将revealView的资源ID保存为一个字段,在构造函数中获取其值,然后在onAttachedToWindow()方法中找到View .

在您发布的代码中,删除最后一行 - 最后一行 finishView = ... - 并将资源 ID 保存到您的字段。

revealViewId = attributes.getResourceId(R.styleable.NetworkLoading_revealView, R.id.revealView);

然后在 onAttachedToWindow() 方法中找到 View

@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();

finishView = ((View) getParent()).findViewById(revealViewId);
...
}

关于android - 从自定义 View 类中的属性中按 ID 获取 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38551485/

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