2011-11-19 72 views
22

這看起來很簡單,但我無法禁用ImageButton。它繼續接收點擊事件,其外觀不會像標準Button那樣改變。我們有一些similar questions SO,但他們不幫我。禁用ImageButton

即使是一個非常簡單的佈局是這樣的:

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

    <ImageButton 
     android:id="@+id/btn_call" 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     android:clickable="false" 
     android:enabled="false" 
     android:src="@android:drawable/sym_action_call" /> 

</LinearLayout> 

按鈕仍處於啓用狀態,我可以點擊它。

奇怪的是,如果我將ImageButton更改爲簡單Button,那麼它的工作方式與預期相同。該按鈕被禁用並且不可點擊。我不明白。有人有想法嗎?

回答

16

ImageButton有不同的繼承鏈意味着它不會延長Button

ImageButton < ImageView < View

繼續接收click事件

這裏是指設置發生了什麼點擊監聽器View

public void setOnClickListener(OnClickListener l) { 
    if (!isClickable()) { 
     setClickable(true); 
    } 
    mOnClickListener = l; 
} 

所以,如果你設置一個監聽器android:clickable="false"變化android:clickable="true"

,其外觀不會改變像一個標準的按鈕將

應提供一個可繪製的狀態列表視圖,以便它可以設置基於android:enabled合適的圖像。你有這個嗎?或者你有唯一的按鈕圖像?

編輯:你可以找到關於StateListDrawable的信息hereandroid:state_enabled是您需要在列表中使用的信息,以便告訴操作系統該狀態使用的圖像。

編輯2:由於您確實需要添加一個偵聽器,您可以在偵聽器if (!isEnabled()) { return; } else { /* process the event */ }中進行檢查。

+0

沒有爲我工作。什麼幫助我通過代碼設置禁用狀態: ImageButton mBtnDelayCall =(ImageButton)v.findViewById(R.id.btnCallDelay); mBtnDelayCall.setEnabled(false); – user2924714

2

確保在您的視圖層次結構中沒有具有相同標識的視圖,並且不會向該視圖添加任何點擊偵聽器。

2

如果要禁用圖像按鈕,在點擊事件中,「的setEnabled」的屬性設置爲false

例:imgButton.setEnabled(false);

+0

android:enabled =「false」不起作用,但使用setEnabled()工作在代碼中設置屬性。 –

38

這裏是我用來禁用ImageButton並使它看起來代碼灰色:

/** 
* Sets the specified image buttonto the given state, while modifying or 
* "graying-out" the icon as well 
* 
* @param enabled The state of the menu item 
* @param item The menu item to modify 
* @param iconResId The icon ID 
*/ 
public static void setImageButtonEnabled(Context ctxt, boolean enabled, ImageButton item, 
     int iconResId) { 
    item.setEnabled(enabled); 
    Drawable originalIcon = ctxt.getResources().getDrawable(iconResId); 
    Drawable icon = enabled ? originalIcon : convertDrawableToGrayScale(originalIcon); 
    item.setImageDrawable(icon); 
} 

/** 
* Mutates and applies a filter that converts the given drawable to a Gray 
* image. This method may be used to simulate the color of disable icons in 
* Honeycomb's ActionBar. 
* 
* @return a mutated version of the given drawable with a color filter 
*   applied. 
*/ 
public static Drawable convertDrawableToGrayScale(Drawable drawable) { 
    if (drawable == null) { 
     return null; 
    } 
    Drawable res = drawable.mutate(); 
    res.setColorFilter(Color.GRAY, Mode.SRC_IN); 
    return res; 
} 

只需致電setImageButtonEnabled();唯一的缺點是你需要在這裏的圖像的資源ID,因爲它是不可能恢復到原來的轉換圖標。