Android開放中要想得到布局文件中控件的引用,該控件必須設置id屬性,這兩有兩種方式設置id:(1)@+id/xxxx;(2)@id/xxxx;下面做個簡單的介紹。

@+id/xxx:如果R文件中沒有該id則創(chuàng)建;
注意:一個xml文件中不能出現(xiàn)兩個以該形式設置同一id的兩個控件(include標簽例外);
示例1 正確的使用:
<TextView android:id="@+id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world"/>
示例2 錯誤(兩個id相同):此時系統(tǒng)會提醒報錯
<TextView android:id="@+id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world"/> <TextView android:id="@+id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world"/>
示例3 允許以下用法,但是該id指向的是include標簽,之后的linearLayout設置id的操作無意義:
<include android:id="@+id/include1" layout="@layout/my" android:layout_width="50dp" android:layout_height="50dp"/> <LinearLayout android:id="@+id/include1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"/>
如果將include標簽與LinearLayout交換位置則會報錯。
示例 4 允許以下用法,但是該id指向TextView,之后的include標簽和LinearLayout設置id無意義:
<TextView android:id="@+id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world"/> <include android:id="@id/mytv" layout="@layout/my" android:layout_width="50dp" android:layout_height="50dp"/> <LinearLayout android:id="@id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"/>
如果將TextView的位置下移,運行會出錯。如果include中引用的布局存在與TextView相同的id設置,不會報錯但是無意義。
2.@id/xxxx:引用ids.xml中相應的id,與@+id/xxx不同,一旦向ids.xml文件中添加一個id在R.java文件中會生成一個相應的id,無論是否有控件使用該id。
使用示例:
(1)創(chuàng)建ids.xml
<resources> <item name="hello" type="id" /> <item name="hello2" type="id" /> <item name="hello3" type="id" /> <item name="hello4" type="id" /> <item name="hello5" type="id" /> <item name="hello6" type="id" /> <item name="hello7" type="id" /> <item name="hello8" type="id" /> </resources>
(2)使用id
<TextView android:id="@id/hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello 1" /> <TextView android:id="@id/hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello 2" /> <TextView android:id="@id/hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello 3" />
多個控件可以以同樣的方式設置統(tǒng)一id,但是該id只屬于最先使用該id的控件。
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
文章名稱:Android----xml文件中的控件的id設置-創(chuàng)新互聯(lián)
當前鏈接:http://www.chinadenli.net/article38/dgeisp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供ChatGPT、搜索引擎優(yōu)化、手機網(wǎng)站建設、商城網(wǎng)站、App設計、網(wǎng)站內鏈
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內容