如何在代码中设置图像按钮的透明背景?

90

我可以在layout.xml中使用以下代码将ImageButton背景设置为透明:

android:background="@android:color/transparent"

我该如何使用Java代码实现相同的功能?类似于 ib.setBackgroundColor(???);


2
谢谢您的询问,我只是需要那条透明线 :) - CularBytes
7个回答

164

这很简单,您只需要将背景颜色设置为透明即可。

    ImageButton btn=(ImageButton)findViewById(R.id.ImageButton01);
    btn.setBackgroundColor(Color.TRANSPARENT);

33

在您的XML中完成它

<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButtonSettings"
        android:layout_gravity="right|bottom"
        android:src="@drawable/tabbar_settings_icon"
        android:background="@android:color/transparent"/>

13

以下代码应该可以正常工作- imageButton.setBackgroundColor(android.R.color.transparent);


12

不要使用透明或空的布局,否则button(或通用视图)就无法在点击时突出显示!!!

我有同样的问题,最终我从Android API中找到了正确的属性来解决这个问题。它适用于任何视图。

在按钮规格中使用此属性。

android:background="?android:selectableItemBackground"

这需要API 11


2
这正是我所需要的。使用 nulltransparent 可以禁用按钮反馈。 - aks

4
尝试像这样做。
ImageButton imagetrans=(ImageButton)findViewById(R.id.ImagevieID);

imagetrans.setBackgroundColor(Color.TRANSPARENT);

或者

将以下内容包含在res/layout文件夹下的.xml文件中

android:background="@android:color/transparent 

3
如果您想使用Android的R类,请按照以下步骤操作:
textView.setBackgroundColor(ContextCompat.getColor(getActivity(), android.R.color.transparent));

不要忘记将支持库添加到Gradle文件中。
compile 'com.android.support:support-v4:23.3.0'

3

只需在您的图像按钮布局中使用这个

android:background="@null"

使用

 android:background="@android:color/transparent 

或者
 btn.setBackgroundColor(Color.TRANSPARENT);

不能完全透明


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接