【问题标题】:findViewById() returns null when accessing custom view访问自定义视图时 findViewById() 返回 null
【发布时间】: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 总是返回 nullsetContentView(R.layout.activity_main); 之前被调用过。

doorView = (DoorView) this.findViewById(R.id.doorView);

编辑:DoorView 的构造函数:

public DoorView(Context context, AttributeSet attrs) {
    super(context);
}

我错过了什么?

【问题讨论】:

  • ID 不匹配,但这可能只是您发布的问题的编辑。发布您的自定义视图构造函数。
  • @laalto 我这样做了。

标签: android view


【解决方案1】:

您需要将AttributeSet 传递给超级构造函数。

改变

public DoorView(Context context, AttributeSet attrs) {
    super(context);
}

public DoorView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

否则超类读取的属性(例如android:id)不会被设置。

【讨论】:

    【解决方案2】:

    你没有doorView id,你有customView

    你需要使用R.id.customView

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多