1. 程式人生 > >android進階之ToggleButton和Swtich

android進階之ToggleButton和Swtich

ToggleButton和Swtich     android中開關元件常見的則是ToggleButton和Switch,其中ToggleButton是的按下彈起,而Switch則是左右滑動。接下來的例子將兩種開關放在了一起。     1、資原始檔

thumb_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/switch_btn_pressed"/>
    <item android:state_pressed="false" android:drawable="@drawable/switch_btn_normal"/>
</selector>
    tarck_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/switch_btn_bg_green"/>
    <item android:state_checked="false" android:drawable="@drawable/switch_btn_bg_white"/>
</selector>
2、佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="wf.com.switchbuttondemo.MainActivity">
<ToggleButton
    android:id="@+id/tbtn_open"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:textOff="開關關閉"
    android:textOn="開關開啟"
    />
    <Switch
        android:id="@+id/sbtn_open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn=""
        android:textOff=""
        android:thumb="@drawable/thumb_selector"
        android:track="@drawable/track_selector"
        />

</LinearLayout>

3、主程式碼
package wf.com.switchbuttondemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.ToggleButton;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.tbtn_open)
    ToggleButton tbtnOpen;
    @BindView(R.id.sbtn_open)
    Switch sbtnOpen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

    }
}

4、效果圖