Android 从自定义视图类中的属性按ID获取视图

Android 从自定义视图类中的属性按ID获取视图,android,layout,Android,Layout,我想从他的ID、xml中的属性中获取一个视图。我尝试过使用getParent(),但返回空值 XML <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ntwldg="http://schemas.android.com/apk/res-auto" android:orientation="vertical" and

我想从他的ID、xml中的属性中获取一个视图。我尝试过使用
getParent()
,但返回空值

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
。在构造函数中,
视图
尚未添加到其所在的布局中,因此
getParent()
将返回
null
。将
revealView
的资源ID保留为字段,在构造函数中获取其值,然后在
onAttachedToWindow()方法中找到
视图

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

revealViewId = attributes.getResourceId(R.styleable.NetworkLoading_revealView, R.id.revealView);
然后在
onAttachedToWindow()
方法中找到
视图

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

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

有点不清楚你到底在问什么。如果您只是试图获取对
网络加载
视图的引用,并且
findViewById(R.id.revelaview)
成功地返回了
TextView
,那么
findViewById(R.id.network\u加载)
将为您提供
网络加载
视图
视图。我想通过从xml传递这个id从网络加载中获取R.id.revealView。哦,好的,我现在明白了。代码到底在哪里?它是在网络加载的构造函数中还是从中调用的?@MikeM。他在我的帖子里,
finishView
应该是
TextView
不,我的意思是,在
networkload
中,代码块在哪里被调用?你是从构造器那里调用它的吗?
@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

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