我有一个按钮。当我按下按钮时,我必须使文本加粗,否则正常。所以我写了粗体和正常样式。

<style name="textbold" parent="@android:style/TextAppearance">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textStyle">bold</item>
</style>
<style name="textregular" parent="@android:style/TextAppearance">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textStyle">normal</item>
</style>

现在我有一个button_states.xml as:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true"
    style="@style/textbold" />
<item android:state_focused="false" android:state_pressed="true"
    style="@style/textregular" />

<item style="@style/textregular" />
</selector> 

在这个按钮的布局中,我必须让背景也是透明的…我要怎么做呢?我的布局代码是:

<Button android:id="@+id/Btn" android:background="@drawable/button_states" />

如何在我的风格中包含透明的背景?


当前回答

我们可以在Button xml中像下面这样使用属性android:background。

android:background="?android:attr/selectableItemBackground"

或者我们可以用风格

风格= " ?android:attr/borderlessButtonStyle”为透明和无阴影的背景。

其他回答

您可以通过在xml文件中添加以下属性轻松地做到这一点。这段代码经过了大量的测试。

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

你也可以使用: 在你的xml中:

android:background="@null"

或者在代码中:

buttonVariable.setBackgroundColor(Color.TRANSPARENT);

我是用XML实现的

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

尝试新的方法设置背景透明

android:背景= " ?android: attr / selectableItemBackground”

选择器只适用于可绘制对象,而不适用于样式。参考


首先,为了使按钮背景透明,使用以下属性,因为这不会影响材质设计动画:

style="?attr/buttonBarButtonStyle"

有很多方法来设置按钮的样式。看看这个教程。

其次,要使文本在按下时加粗,使用以下java代码:

btn.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            // When the user clicks the Button
            case MotionEvent.ACTION_DOWN:
                btn.setTypeface(Typeface.DEFAULT_BOLD);
                break;

            // When the user releases the Button
            case MotionEvent.ACTION_UP:
                btn.setTypeface(Typeface.DEFAULT);
                break;
        }
        return false;
    }
});