【发布时间】:2018-01-04 10:48:13
【问题描述】:
我创建了一个继承自 android.view.View; 的自定义视图并将此视图添加到活动中:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="...MainActivity">
<view
android:id="@+id/doorView"
class="CustomView"
android:layout_width="0dp"
android:layout_height="220dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/..."/>
</android.support.constraint.ConstraintLayout>
问题:findViewById 总是返回 null。 setContentView(R.layout.activity_main); 之前被调用过。
doorView = (DoorView) this.findViewById(R.id.doorView);
编辑:DoorView 的构造函数:
public DoorView(Context context, AttributeSet attrs) {
super(context);
}
我错过了什么?
【问题讨论】:
-
ID 不匹配,但这可能只是您发布的问题的编辑。发布您的自定义视图构造函数。
-
@laalto 我这样做了。