2011-01-28 26 views
1

我想要達到的效果是,一旦按下,ImageButton就會用「按下」橙色背景繪製,直到失去焦點(其他東西被觸摸)。Android:如何繪製一個ImageButton使用可壓縮狀態繪製爲聚焦狀態

StateListDrawable似乎適用於這種情況,因爲它可以讓我定義如何爲聚焦狀態繪製背景。如果我可以簡單地定義背景應該用按下的drawable繪製,那對於聚焦狀態來說就好了。但是,我看不出引用默認的「按下」可繪製的方式。

有關如何達到此效果的任何建議?

回答

1

查看android SDK中的drawables文件夾。您可以在默認情況下找到它使用的所有九個補丁映像。你想要的可能叫做btn_pressed,btn_focused等。或者類似的東西。您可以在技術上通過您的項目中的id來引用它們,但我相信建議您將它們複製到您的項目中,因爲ID不會保持不變。

+0

謝謝。我將此標記爲已回答,因爲它確實回答了我的問題,但實際上並未解決我的問題。問題結果是,圖像按鈕丟失集中在觸摸的「向上」事件。我希望imagebutton能夠保持焦點,直到其他東西抓住它爲止(這樣它纔會被聚焦,直到其他東西被觸摸)。對此有何建議? – ab11 2011-01-28 19:15:46

5

如果我明白你的問題,也許可以幫助你

我做定義XML背景選擇,包含可繪每個狀態相同的任務,這個文件是更廣泛的,因爲你可以定義可繪製形狀等等。 ..最重要的特點是,你可以設置任何可繪製或你想要的形狀...

這裏我定義了我的背景選擇器...我稱之爲selector.xml並保存到可繪製的文件夾。

<?xml version="1.0" encoding="utf-8"?> 
    <selector xmlns:android="http://schemas.android.com/apk/res/android"> 
     <item android:state_selected="true" android:drawable="@drawable/shape_7"/> 
     <item android:state_pressed="true" android:drawable="@drawable/shape_7" /> 
     <item android:state_pressed="false" android:drawable="@drawable/shape_6" /> 
    </selector> 

後來當我建立的ImageButton附上上述選擇......(你可以通過程序或在你的XML佈局做)

ImageButton imageButton = new ImageButton(this); 
imageButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector)); 

或XML的方式

<ImageView 
    android:background="@drawable/selector" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="4px" 
    android:src="@drawable/switch_icon"/> 

歡呼聲

+2

這是有益的,但是,可能最主要的問題是,我想選擇的壓縮並重點可繪製成Android默認。反正有定義shape_7和shape_6,以便它們使用默認的android drawalbes? (當我說默認的android drawables時,我的意思是如果沒有設置自定義背景時使用的那些) – ab11 2011-01-28 17:59:51

0

這是在我的應用程序的Holo黑暗主題中爲我工作,但它沒有我想要的圓形邊緣。

RES /繪製/ image_button_background.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@android:color/holo_blue_dark" android:state_pressed="true"/> 
</selector> 

用途爲:

android:background="@drawable/image_button_background"