【问题标题】:Button size and background color change on button press按下按钮时按钮大小和背景颜色发生变化
【发布时间】:2025-12-09 11:00:02
【问题描述】:

我正在尝试创建一个包含 3 个按钮的布局,我想让每个按钮的宽度为屏幕宽度的 30%。 最好的方法是什么?

我的第二个问题是, 如何定义按钮的按下颜色? 我希望按钮为绿色,按下时变为红色。

谢谢! 马可

【问题讨论】:

  • 你想让它们在发布后再次变绿吗?

标签: android layout button


【解决方案1】:

为按钮着色的最佳方法是在按下/活动/禁用/聚焦时为您的按钮创建自定义可绘制对象(在我的示例中,我使用 button_faded.png、button_down.png 和 button_up.png)然后定义一个xml 告诉按钮如何使用它:

button.xml:

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

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_faded"
          android:state_enabled="false" />
    <item android:drawable="@drawable/button_down"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_up"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_up" />
</selector>

然后在你的布局中将背景设置为"@drawable/button"

或者更好的是在你的styles.xml中创建一个按钮样式:

<style name="Button">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#000000</item>
    <item name="android:textSize">19sp</item>
    <item name="android:background">@drawable/button</item>
    <item name="android:gravity">center</item>
    <item name="android:paddingLeft">0dp</item>
    <item name="android:paddingRight">0dp</item>
    <item name="android:paddingTop">5dp</item>
    <item name="android:paddingBottom">5dp</item>
</style>

并在您的布局 xml 中告诉按钮使用样式:

    <Button style="@style/Button" />

至于按钮的布局...如果您正在寻找每个屏幕的 1/3,请创建一个包含所有三个按钮的水平 LinearyLayout。将按钮宽度设置为 fill_parent 并给它们所有相同的布局权重,比如说“1”...这应该用 3 个按钮填充该行,每个按钮的大小都相同。然后,您可以使用布局边距或内边距调整它们之间的间距。

【讨论】:

    【解决方案2】:
    Display mDisplay= activity.getWindowManager().getDefaultDisplay();
    int width= mDisplay.getWidth();
    int Height= mDisplay.getHeight();
    
    if(width>height)
    {
    //Landscape
    //set your landscape drawable
    }
    else
    {
    //portrait
    //set your portrait drawable
    }
    

    现在取 30% 的宽度变量,对于颜色,只需使用具有不同状态的可绘制对象,请参阅 here

    【讨论】: