【Android】ImageButton的記錄

官網(wǎng)介紹:鏈接

ImageButton繼承于ImageView。

ImageButton跟Button不一樣,它用圖片取代文字。
它默認(rèn)看起來(lái)就像一個(gè)能夠在不同狀態(tài)(點(diǎn)擊、按住、松開等等)改變顏色的普通Button。
ImageButton上的圖像,可以通過(guò)android:src這個(gè)XML屬性,
或者setImageResource(int)這個(gè)方法來(lái)定義。

To indicate the different button states (focused, selected, etc.), you can define a different image for each state. E.g., a blue image by default, an orange one for when focused, and a yellow one for when pressed. An easy way to do this is with an XML drawable "selector." For example:

你可以給ImageButton不同的狀態(tài)定義不同的圖片,
例如默認(rèn)情況是藍(lán)色的,獲得焦點(diǎn)時(shí)是橙色的,被點(diǎn)擊時(shí)是黃色的。
這種效果用一個(gè)XML的drawable資源 "selector"就很容易實(shí)現(xiàn)了,例如:

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/button_pressed" /> <!-- pressed -->
     <item android:state_focused="true"
           android:drawable="@drawable/button_focused" /> <!-- focused -->
     <item android:drawable="@drawable/button_normal" /> <!-- default -->
 </selector>

保存XML文件在項(xiàng)目的res/drawable/目錄,并且將其聲明為你的ImageButton的來(lái)源(就是android:src那個(gè)屬性)。Android就會(huì)基于按鈕的狀態(tài),自動(dòng)將按鈕改變?yōu)橄鄳?yīng)的圖像。

【注意】上面<selector/>里面的元素怎么排序很關(guān)鍵,因?yàn)樗鼈兪前错樞虮辉u(píng)估的。這就是為什么 "normal"會(huì)在最后,因?yàn)椤捌胀ā钡臓顟B(tài)只會(huì)在既不是“取得焦點(diǎn)”狀態(tài)也不是“被點(diǎn)擊”狀態(tài)時(shí)產(chǎn)生。(這句真的不知道怎么翻譯,放原文吧。)

The order of the elements is important because they are evaluated in order. This is why the "normal" button image comes last, because it will only be applied afterandroid:state_pressed and android:state_focused have both evaluated false.

我的上機(jī)記錄

剛開始只看了官網(wǎng)一半的介紹就開始操作,
以為跟Button的屬性一樣,結(jié)果發(fā)現(xiàn)不是。

res/layout/的布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/ib_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ib_test" />

</LinearLayout>

res/drawable/的<selector />狀態(tài):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ib_test2" android:state_pressed="true" />
    <!-- pressed -->
    <item android:drawable="@drawable/ib_test1" />
    <!-- default -->
</selector>

這里我剛開始還以為要放在“res/layout/”,結(jié)果就是提示出錯(cuò)。

效果就是下面這樣:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容