android进阶之ToggleButton和Swtich

版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/ckq5254/article/details/54947791
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、效果图





阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页