安卓开发笔记(二十八):仿写IOS switch选择器控件实现,checkbox

版权声明:Geek Song创造,版权所有 https://blog.csdn.net/Geeksongs/article/details/89529994

安卓开发笔记(二十八):仿写IOS switch选择器控件实现,checkbox

我们先来看看效果:

这里我们主要使用了github上的一个开源项目,配置起来比较方便,下面解释一下该如何使用:
首先是:
Gradle文件当中进行配置:

dependencies {
  
    implementation 'ch.ielse:switchbutton:1.0.1'
   
}

当然如果是老版本的Android Studio则使用:

dependencies {
  
    complie 'ch.ielse:switchbutton:1.0.1'
   
}

二.activity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import ch.ielse.view.SwitchView;

public class PrimaryColor extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.primary_color);
        SwitchView switchView=(SwitchView)findViewById(R.id.button);
        switchView.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                view.toggleSwitch(true); // or false
                Toast.makeText(PrimaryColor.this,"您触发了这个事件",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void toggleToOff(SwitchView view) {
                view.toggleSwitch(false); // or true
            }
        });


    }
}

其中的第一个监听器是switch在选择的时候,所触发的事件。第二个监听器是未在选择的时候,所触发的事件。这样使用起来比较方便。

 三.actvity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".PrimaryColor">
    <ch.ielse.view.SwitchView
        android:layout_margin="150dp"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

得解,一共就只有这三个部分了,很容易的,如果自己去写,不调用开源库的话将会浪费很多时间。

posted @ 2019-04-25 10:54 Geeksongs 阅读( ...) 评论( ...) 编辑 收藏

猜你喜欢

转载自blog.csdn.net/Geeksongs/article/details/89529994