2015年9月4日 星期五

【Android】客製化有圓角的Button (不用圖片)



=======================CheckableButton.java=======================
package com.tsots.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.Checkable;

public class CheckableButton extends Button implements Checkable {

private boolean mChecked;

private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

public CheckableButton(Context context) {
  super(context);
}

public CheckableButton(Context context, AttributeSet attrs) {
  super(context, attrs);
}

@Override
public int[] onCreateDrawableState(int extraSpace) {
  final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
  if (isChecked()) {
   mergeDrawableStates(drawableState, CHECKED_STATE_SET);
  }
  return drawableState;
}

@Override
public boolean isChecked() {
  return mChecked;
}

@Override
public void setChecked(boolean checked) {
  if (mChecked != checked) {
   mChecked = checked;
   refreshDrawableState();
  }
}

@Override
public void toggle() {
  setChecked(!mChecked);
}

}

=======================button_background.xml=======================
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <corners android:radius="80dip" />

            <solid android:color="@color/background_selected" />
        </shape>
</item>
    <item android:state_checked="true">
        <shape android:shape="rectangle">
            <corners android:radius="80dip" />

            <solid android:color="@color/background_selected" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <corners android:radius="80dip" />

            <solid android:color="@color/background_selected" />
        </shape>
</item>
    <item>
        <shape android:shape="rectangle">
            <corners android:radius="80dip" />
            <solid android:color="@color/background_normal" />
        </shape>
</item>

</selector>

=======================colors.xml=======================
<color name="background_normal">#1ec20d</color>                          
<color name="background_selected">#0C635B</color>
<color name="white">#FFFFFF</color>
=======================main_layout.xml=======================
<com.tsots.widget.CheckableButton
            android:id="@+id/service_btn"
            android:layout_width="120dp"
            android:layout_height="30dp"
            android:layout_centerHorizontal="true"
            android:background="@drawable/button_background"
            android:text="登入"
            android:textColor="@color/white"
            android:textSize="24dp"
            />

沒有留言:

張貼留言