按钮按钮上的按钮大小和背景颜色更改

时间:2011-08-17 18:21:09

标签: android layout button

我正在尝试创建一个排列有3个按钮的布局,我想让它们中的每一个都宽度为屏幕宽度的30%。 最好的方法是什么?

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

谢谢! 马可

2 个答案:

答案 0 :(得分:5)

为按钮执行颜色的最佳方法是在按下/激活/禁用/聚焦时为您创建自定义可绘制按钮(在我的示例中,我使用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个按钮填充行,每个按钮的大小相同。然后,您可以使用布局边距或填充来调整它们之间的空间。

答案 1 :(得分:1)

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%,而对于颜色,只需使用不同状态的drawable,请参阅here