自定义视图 xml 及其用法

Custom view xml versus its usage

我有一个自定义视图 CustomSettingEntry 这是它的 xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/layout_custom_setting_entry_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/custom_setting_entry_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </RelativeLayout>
</LinearLayout>

然后我在片段中使用它并为其分配一个 id:

<com.mypackage.name.CustomSettingEntry
                android:id="@+id/layout_notification_setting"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:setting_title="@string/title"
                app:setting_subtitle="@string/subtitle" />

我的问题是id为layout_custom_setting_entry_container的LinearLayout和id为layout_notification_setting的用法有什么区别?他们指的是同一个东西吗?

如果我在片段内的自定义视图上设置点击监听器,然后在某些情况下禁用点击自定义视图内的根 LinearLayout,这会停止监听器吗?

我知道您的自定义视图是 LinearLayout 的子 class,它会膨胀 xml 布局。如果是,则生成的视图层次结构为

[LinearLayout (actually a CustomSettingEntry), id : layout_notification_setting]
    [LinearLayout, id : layout_custom_setting_entry_container]
        ... 

所以有两个级别的视图组,每个级别都有自己的 ID。

顺便说一下,这是低效的,因为外部视图组(您的自定义 class)只有一个 child(xml 的根)。

解决方案是使用 <merge> 作为 xml 布局的根以跳过一级。参见 Optimize by merging or Inflating layout for your custom view 了解更多详情。