在布局中使用包含指令定义的按钮的资源 ID XML
Resource ID of Button Defined Using Include Directive in Layout XML
我遇到了一个应用程序,它的布局让我很困惑。
假设有两个布局 XML 文件,一个包含另一个:
activity_button.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/button"/>
</LinearLayout>%
button.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/button"
android:onClick="sendMessage">
</Button>
按钮的资源 ID 是什么?
我认为人们总是必须通过 android:id
属性指定 ID,所以我很困惑为什么这种布局有效。我还检查了 R.java
ID 条目,它似乎是空的。
What is the resource ID of the button?
没有
I thought one always had to specify ID via android:id
attribute
你为什么这么想?对于大多数布局的根视图,您通常会忽略此属性。 (请参阅您的问题 LinearLayout
)
如果您从没想过使用 ID 找到视图,则不需要 android:id
。由于 onClick 是在 XML 中定义的,因此查找按钮实际上没有任何意义。
android:id
不是布局 xml 文件中视图的必填字段。仅有的两个必填字段是视图的宽度和高度。
想一想您希望布局仅显示一些标题而无需任何业务需要在 activity 生命周期内更改它的情况。为此您不需要获取此视图 ID,也不需要为此视图创建 ID 的开销
我遇到了一个应用程序,它的布局让我很困惑。
假设有两个布局 XML 文件,一个包含另一个:
activity_button.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/button"/>
</LinearLayout>%
button.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/button"
android:onClick="sendMessage">
</Button>
按钮的资源 ID 是什么?
我认为人们总是必须通过 android:id
属性指定 ID,所以我很困惑为什么这种布局有效。我还检查了 R.java
ID 条目,它似乎是空的。
What is the resource ID of the button?
没有
I thought one always had to specify ID via
android:id
attribute
你为什么这么想?对于大多数布局的根视图,您通常会忽略此属性。 (请参阅您的问题 LinearLayout
)
如果您从没想过使用 ID 找到视图,则不需要 android:id
。由于 onClick 是在 XML 中定义的,因此查找按钮实际上没有任何意义。
android:id
不是布局 xml 文件中视图的必填字段。仅有的两个必填字段是视图的宽度和高度。
想一想您希望布局仅显示一些标题而无需任何业务需要在 activity 生命周期内更改它的情况。为此您不需要获取此视图 ID,也不需要为此视图创建 ID 的开销