禁用ImageButton

Dal*_*mas 24 android imagebutton

这看起来很简单,但我无法禁用ImageButton.它继续接收点击事件,其外观不会像标准的Button那样改变.

关于SO 有一些类似的问题,但它们对我没有帮助.

即使有这样一个非常简单的布局:

<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>
Run Code Online (Sandbox Code Playgroud)

该按钮仍然启用,我可以单击它.

奇怪的是,如果我将其更改ImageButton为简单Button,那么它将按预期工作.该按钮变为禁用且无法点击.我不明白.有没有人有想法?

Ole*_*ich 45

这是我用来禁用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;
}
Run Code Online (Sandbox Code Playgroud)

只需打电话setImageButtonEnabled(); 唯一的缺点是你需要这里的图像资源ID,因为无法将转换后的图标恢复为原始图标.


Vit*_*nko 17

ImageButton具有不同的继承链意味着它不会扩展Button:

ImageButton< ImageView<View

它继续接收点击事件

以下是为以下内容设置单击侦听器时发生的情况View:

public void setOnClickListener(OnClickListener l) {
    if (!isClickable()) {
        setClickable(true);
    }
    mOnClickListener = l;
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您将侦听器设置android:clickable="false"android:clickable="true".

它的外观不会像标准的Button那样改变

您应该为视图提供可绘制状态列表,以便它可以基于设置适当的图像android:enabled.你有这个吗?或者你有唯一的按钮图像?

编辑:您可以在这里找到关于StateListDrawable的信息.android:state_enabled是您需要在列表中使用的,以告诉操作系统该状态使用什么图像.

编辑2:因为你真的需要添加一个监听器,你可以在监听器内部进行检查if (!isEnabled()) { return; } else { /* process the event */ }.


Rom*_*ius 7

如果要禁用图像按钮,请在单击事件时将属性“setEnabled”设置为 false

前任:imgButton.setEnabled(false);

  • android:enabled="false" 不起作用,但使用 setEnabled() 在代码中设置属性可以。 (3认同)