开发者

Button size and background color change on button press

I'm trying to create a layout with 3 buttons in line, and I'd like to make each one of them width 30% of the screen width. What's the best way to do this?

My second question is, how do I define the on开发者_StackOverflow社区 press color for the button? I would like the buttons to be GREEN and turn RED when pressed.

Thanks! Marco


The best way to do the color for the buttons is to create custom drawables for you button when pressed/active/disabled/focused (in my example I use button_faded.png, button_down.png & button_up.png) then define an xml to tell the button how to use it:

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>

Then in your layout set the background to "@drawable/button"

or better yet in your styles.xml create a button style:

<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>

and in your layout xml tell the button to use the style:

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

As far as the layout of the buttons... if you are looking for 1/3 of the screen each, create a horizontal LinearyLayout that contains all three buttons. Set the buttons width to fill_parent and give them all the same layout weight of let's say '1'... This should fill the row with the 3 buttons each the same size. You can then adjust the space between them using the layout margins or padding.


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
}

now take the 30% of width variable, and for color just use drawable with different states see here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜