![](/img/trans.png)
[英]Android source code and repo - What exactly is happening when getting code
[英]What is happening when I type @+id in Android?
Android XML中的許多標識符都需要@
前綴作為對XML中其他位置定義的值的引用。
例如
@drawable/transparent
@color/red
@string/hello_world
但是,id的奇怪之處在於語法不同:
@+id/my_id
顯然,與其他標識符一起,我們正在引用一個大概在其他地方定義的資源,而對於id,我們正在創建該標識符。 為什么使用@+
的語法? 我對這種語法的真正含義感到好奇,並且是否還有@+id
以外的其他用途(是否有@+string
或@+color
嗎?)。
但是,id很奇怪,因為語法不同
語法有時會有所不同。
為什么使用@ +的語法?
表示我們正在專門創建一個標識符,而@id/...
表示我們正在引用一個應該早已在此資源文件中定義的標識符。
例如:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/entry"
android:layout_alignParentLeft="true"
android:text="@string/url"/>
<EditText
android:id="@id/entry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@id/label"
android:inputType="text"/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@id/entry"
android:layout_below="@id/entry"
android:text="@string/ok"/>
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/ok"
android:layout_toLeftOf="@id/ok"
android:text="@string/cancel"/>
</RelativeLayout>
我對label
和entry
標識符的第二次引用使用@id/
,指示該標識符應該已經在文件的前面定義了。
早於拖放式GUI構建器之類的日子,這將有助於在編譯時檢測ID不匹配。 例如,如果我輸入@id/ernty
而不是@id/entry
,則會出現編譯錯誤,因為文件中不存在@+id/ernty
。
如果除了@ + id之外還有其他用途
我什么都不知道。
'@ id /':表示my_id
是一個ID
'@ + id / ...':表示您創建一個新ID。
因此,當您在布局中定義視圖的ID時,可以使用@+id/my_id
,但是在引用它時(例如,在android:layout_below中),則可以使用@id/my_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.