2016-12-04 113 views
0

我注意到一个应用程序,它的布局让我为难,来到include指令。资源ID定义使用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条目,它似乎是空的。

回答

1

机器人:ID

是不适合的布局xml文件的视图必填字段。唯一的两个必填字段是视图的宽度和高度。

想想当您希望布局仅显示某个标题而无需任何业务的情况下,需要通过活动生命周期来更改它。这需要你不需要获得这一观点的ID,并且不需要创建ID的开销这一观点

1

按钮的资源ID是什么?

不具有一个

我认为一个总是通过android:id属性

指定ID你为什么这样认为?您经常忽略此属性以查看大多数布局的根视图。 (请参阅您的问题的LinearLayout

如果您从不期望使用ID查找视图,则不需要android:id。由于onClick是在XML中定义的,因此找到该按钮确实没有任何用处。