├── .gitignore
├── .idea
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
└── runConfigurations.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── qiangxi
│ │ └── switchviewproject
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── qiangxi
│ │ │ └── switchviewproject
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── qiangxi
│ └── switchviewproject
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── image
├── image.png
├── 效果2.gif
├── 效果3.png
└── 默认.gif
├── settings.gradle
└── switchview
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── com
│ └── qiangxi
│ └── switchview
│ └── ExampleInstrumentedTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── com
│ │ └── qiangxi
│ │ └── switchview
│ │ ├── SwitchView.java
│ │ └── callback
│ │ └── OnItemSelectedListener.java
└── res
│ ├── drawable
│ └── bg_selected_drawable.xml
│ └── values
│ ├── attrs.xml
│ └── strings.xml
└── test
└── java
└── com
└── qiangxi
└── switchview
└── ExampleUnitTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | 1.8
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SwitchViewProject
2 | ## 对应的文章
3 | [关于SwitchView简单解读的文章](http://blog.csdn.net/qiang_xi/article/details/74942386)
4 | ### 效果图:
5 | ##### 默认效果
6 | 
7 | ##### 自定义文本及字体颜色、大小
8 | 
9 | ##### 自定义插值器,锁定位置(锁定位置为2),滑动时不展示文本
10 | 
11 |
12 | ### 更新日志
13 | #### 2017-07-11
14 | 发布第一个稳定版本V1.0.0。
15 |
16 | ### 集成方式
17 | #### gradle:
18 | ```grooxy
19 | compile 'com.qiangxi.switchview:switchview:1.0.0'
20 | ```
21 | #### maven:
22 | ```maven
23 |
24 | com.qiangxi.switchview
25 | switchview
26 | 1.0.0
27 | pom
28 |
29 | ```
30 | ### API说明
31 | API | API调用时机 | 对应的xml属性|作用
32 | ---|---|---|---
33 | setOnItemSelectedListener(OnItemSelectedListener listener) | view初始化后的任意时刻|无|设置item选中监听,当item被选中时触发回调
34 | setScrollEnable(boolean scrollEnable)|view初始化后的任意时刻|app:scrollEnable="boolean"|设置是否禁用滑动手势【true:不禁用;false:禁用;默认为true】
35 | smoothScrollTo(int position)|需要动态滑动时调用|无|平滑移动到指定位置【注意与setDefaultSelectedPosition(int position)方法区分开来。】
36 | setShowTextWhenScrolling(boolean isShowText)|view初始化后的任意时刻|app:showTextWhenScrolling="boolean"|滑块在滑动时是否在滑块上显示文本【true:显示;false:不显示;默认为true】
37 | setInterpolator(TimeInterpolator interpolator)|view初始化后的任意时刻|无|设置滑动插值器
38 | setLockPosition(int position)|view初始化后的任意时刻|app:lockedPosition="interger"|指定锁定位置【位置被锁定后,该位置不可点击,且滑块滑动到该位置松开后,会自动滑动到原位置;只能指定一个位置为锁定位置】
39 | unlockPosition()|view初始化后的任意时刻|无|解锁被锁定的位置【解锁后,所有位置都自由了】
40 | getLockPosition()|view初始化后的任意时刻|无|获取被锁定的位置【未设置锁定位置时返回-1】
41 | getTotalItemCount()|view初始化后的任意时刻|无|获取item总数量
42 | setNormalTextColor(int normalTextColor)|view初始化后的任意时刻|app:normalTextColor="color"|设置默认文本颜色【未设置则使用默认】
43 | setNormalTextSize(float normalTextSize)|view初始化后的任意时刻|app:normalTextSize="dimension"|设置默认文本字体大小【未设置则使用默认】
44 | setSelectedTextColor(int selectedTextColor)|view初始化后的任意时刻|app:selectedTextColor="color"|设置选中文本颜色【未设置则使用默认】
45 | setSelectedTextSize(float selectedTextSize)|view初始化后的任意时刻|app:selectedTextSize="dimension"|设置选中文本字体大小【未设置则使用默认】
46 | setSelectedDrawableResId(@DrawableRes int selectedDrawableResId)|view初始化后的任意时刻|app:selectedDrawableResId="integer"|设置选中的item的背景drawable【未设置则使用默认】
47 | setSelectedBgMarginArray(int[] selectedBgMarginArray) |view初始化时调用|无|设置滑块距离四周的margin值【整型数组,位置对应关系:[left,top,right,bottom],数组长度必须为4】
48 | setDefaultSelectedPosition(int position)|view初始化时调用|app:defaultSelectedPosition="integer"|设置滑块初始位置【未设置则使用默认值,即0位置】
49 | setTextArray(String[] textArray)|view初始化时调用|app:textArray="reference"|设置文本内容【使用xml属性时,按照如下方式使用:app:textArray="@array/customTextArray"】
50 | getSlideView()|view初始化后的任意时刻|无|获取滑块view【目前是TextView,将来可能会继承TextView自定义一个SlideView】
51 | setEnable(boolean enable)|view初始化后的任意时刻|无|是否禁用所有手势【true:不禁用;false:禁用;禁用之后,不在响应任何手势,包括点击和滑动】
52 | isEnable()|view初始化后的任意时刻|无|是否已经禁用所有手势
53 |
54 | ### 基本使用方式
55 | ```java
56 | public class MainActivity extends AppCompatActivity {
57 | private String[] textArray = {"文本一", "文本二", "文本三", "文本四", "文本五"};
58 | private SwitchView mSwitchView;
59 |
60 | private int[] marginArray = {20, 20, 20, 20};
61 | private boolean isRequestSuccess;
62 |
63 | @Override
64 | protected void onCreate(Bundle savedInstanceState) {
65 | super.onCreate(savedInstanceState);
66 | setContentView(R.layout.activity_main);
67 | mSwitchView = (SwitchView) findViewById(switchView);
68 | // mSwitchView.setTextArray(textArray);
69 | // mSwitchView.setNormalTextColor(Color.GREEN);
70 | // mSwitchView.setNormalTextSize(15);
71 | // mSwitchView.setSelectedDrawableResId(R.mipmap.ic_launcher);
72 | // mSwitchView.setSelectedTextColor(Color.BLUE);
73 | // mSwitchView.setSelectedTextSize(18);
74 |
75 | // mSwitchView.setLockPosition(2);
76 | // mSwitchView.setSelectedBgMarginArray(marginArray);
77 | // mSwitchView.setDefaultSelectedPosition(0);
78 | // mSwitchView.setInterpolator(new OvershootInterpolator());
79 | // mSwitchView.setShowTextWhenScrolling(false);
80 | mSwitchView.setOnItemSelectedListener(new OnItemSelectedListener() {
81 | @Override
82 | public void onItemSelected(int currentSelectedPosition, final int lastSelectedPosition) {
83 | //模拟网络请求
84 | new Handler().postDelayed(new TimerTask() {
85 | @Override
86 | public void run() {
87 | if (isRequestSuccess) {
88 | //若请求成功,do nothing
89 | } else {
90 | //若请求失败,调用如下方法移动到上一个位置
91 | mSwitchView.smoothScrollTo(lastSelectedPosition);
92 | }
93 | }
94 | }, 2000);
95 | // Toast.makeText(MainActivity.this, "currentSelectedPosition=" + currentSelectedPosition + ",lastSelectedPosition=" + lastSelectedPosition, Toast.LENGTH_SHORT).show();
96 | }
97 | });
98 | }
99 |
100 | public void click(View view) {
101 |
102 | // mSwitchView.setScrollEnable(false);
103 | // mSwitchView.setNormalTextColor(Color.GREEN);
104 | // mSwitchView.setNormalTextSize(25);
105 | // mSwitchView.setSelectedDrawableResId(R.mipmap.ic_launcher);
106 | // mSwitchView.setSelectedTextColor(Color.BLUE);
107 | // mSwitchView.setSelectedTextSize(50);
108 |
109 |
110 | // mSwitchView.unlockPosition();//有效
111 |
112 | }
113 | }
114 | ```
115 | ### 最后
116 | 如果该项目对你有帮助,还请不吝赏赐star或fork。也欢迎提出issue或pr,一起维护这个项目。
117 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.0"
6 | defaultConfig {
7 | applicationId "com.qiangxi.switchviewproject"
8 | minSdkVersion 16
9 | targetSdkVersion 25
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | dataBinding {
21 | enabled = true
22 | }
23 | }
24 |
25 | dependencies {
26 | compile fileTree(include: ['*.jar'], dir: 'libs')
27 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
28 | exclude group: 'com.android.support', module: 'support-annotations'
29 | })
30 | compile 'com.android.support:appcompat-v7:25.0.0'
31 | testCompile 'junit:junit:4.12'
32 | compile project(':switchview')
33 | }
34 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Android\AndroidSDK/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/qiangxi/switchviewproject/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.qiangxi.switchviewproject;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.qiangxi.switchviewproject", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/com/qiangxi/switchviewproject/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.qiangxi.switchviewproject;
2 |
3 | import android.os.Bundle;
4 | import android.os.Handler;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.view.View;
7 |
8 | import com.qiangxi.switchview.SwitchView;
9 | import com.qiangxi.switchview.callback.OnItemSelectedListener;
10 |
11 | import java.util.TimerTask;
12 |
13 | import static com.qiangxi.switchviewproject.R.id.switchView;
14 |
15 | public class MainActivity extends AppCompatActivity {
16 | private String[] textArray = {"文本一", "文本二", "文本三", "文本四", "文本五"};
17 | private SwitchView mSwitchView;
18 |
19 | private int[] marginArray = {20, 20, 20, 20};
20 | private boolean isRequestSuccess;
21 |
22 | @Override
23 | protected void onCreate(Bundle savedInstanceState) {
24 | super.onCreate(savedInstanceState);
25 | setContentView(R.layout.activity_main);
26 | mSwitchView = (SwitchView) findViewById(switchView);
27 | // mSwitchView.setTextArray(textArray);
28 | // mSwitchView.setNormalTextColor(Color.GREEN);
29 | // mSwitchView.setNormalTextSize(15);
30 | // mSwitchView.setSelectedDrawableResId(R.mipmap.ic_launcher);
31 | // mSwitchView.setSelectedTextColor(Color.BLUE);
32 | // mSwitchView.setSelectedTextSize(18);
33 |
34 | // mSwitchView.setLockPosition(2);
35 | // mSwitchView.setSelectedBgMarginArray(marginArray);
36 | // mSwitchView.setDefaultSelectedPosition(0);
37 | // mSwitchView.setInterpolator(new OvershootInterpolator());
38 | // mSwitchView.setShowTextWhenScrolling(false);
39 | mSwitchView.setOnItemSelectedListener(new OnItemSelectedListener() {
40 | @Override
41 | public void onItemSelected(int currentSelectedPosition, final int lastSelectedPosition) {
42 | //模拟网络请求
43 | new Handler().postDelayed(new TimerTask() {
44 | @Override
45 | public void run() {
46 | if (isRequestSuccess) {
47 | //若请求成功,do nothing
48 | } else {
49 | //若请求失败,调用如下方法移动到上一个位置
50 | mSwitchView.smoothScrollTo(lastSelectedPosition);
51 | }
52 | }
53 | }, 2000);
54 | // Toast.makeText(MainActivity.this, "currentSelectedPosition=" + currentSelectedPosition + ",lastSelectedPosition=" + lastSelectedPosition, Toast.LENGTH_SHORT).show();
55 | }
56 | });
57 | }
58 |
59 | public void click(View view) {
60 |
61 | // mSwitchView.setScrollEnable(false);
62 | // mSwitchView.setNormalTextColor(Color.GREEN);
63 | // mSwitchView.setNormalTextSize(25);
64 | // mSwitchView.setSelectedDrawableResId(R.mipmap.ic_launcher);
65 | // mSwitchView.setSelectedTextColor(Color.BLUE);
66 | // mSwitchView.setSelectedTextSize(50);
67 |
68 |
69 | // mSwitchView.unlockPosition();//有效
70 |
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
15 |
16 |
22 |
23 |
29 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SwitchViewProject
3 |
4 | - 文本一
5 | - 文本二
6 | - 文本三
7 | - 文本四
8 | - 文本五
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/qiangxi/switchviewproject/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.qiangxi.switchviewproject;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.3'
9 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
10 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
11 | // NOTE: Do not place your application dependencies here; they belong
12 | // in the individual module build.gradle files
13 | }
14 | }
15 |
16 | allprojects {
17 | repositories {
18 | jcenter()
19 | }
20 | }
21 |
22 | task clean(type: Delete) {
23 | delete rootProject.buildDir
24 | }
25 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Jul 03 09:10:17 CST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/image/image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/image/image.png
--------------------------------------------------------------------------------
/image/效果2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/image/效果2.gif
--------------------------------------------------------------------------------
/image/效果3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/image/效果3.png
--------------------------------------------------------------------------------
/image/默认.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qiangxi/SwitchViewProject/6b1197b25b7dbd14e1a0c1f02ea54a4f4f4d4a00/image/默认.gif
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':switchview'
2 |
--------------------------------------------------------------------------------
/switchview/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/switchview/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.jfrog.bintray'
3 | apply plugin: 'com.github.dcendents.android-maven'
4 |
5 | version = "1.0.0"
6 | android {
7 | compileSdkVersion 25
8 | buildToolsVersion "25.0.0"
9 |
10 | defaultConfig {
11 | minSdkVersion 16
12 | targetSdkVersion 25
13 | versionCode 1
14 | versionName version
15 |
16 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
17 |
18 | }
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | }
26 |
27 | dependencies {
28 | compile fileTree(dir: 'libs', include: ['*.jar'])
29 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
30 | exclude group: 'com.android.support', module: 'support-annotations'
31 | })
32 | compile 'com.android.support:appcompat-v7:25.0.0'
33 | testCompile 'junit:junit:4.12'
34 | }
35 | def siteUrl = 'https://github.com/qiangxi/SwitchViewProject' // 项目的主页
36 | def gitUrl = 'https://github.com/qiangxi/SwitchViewProject.git' // Git仓库的url
37 | group = "com.qiangxi.switchview" //一般填你唯一的包名
38 | install {
39 | repositories.mavenInstaller {
40 | // This generates POM.xml with proper parameters
41 | pom {
42 | project {
43 | packaging 'aar'
44 | // Add your description here
45 | name 'switchview' //项目描述
46 | url siteUrl
47 | // Set your license
48 | licenses {
49 | license {
50 | name 'The Apache Software License, Version 2.0'
51 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
52 | }
53 | }
54 | developers {
55 | developer {
56 | id 'qiang_xi' //填写的一些基本信息
57 | name 'renqiangqiang'
58 | email 'renqiangqiang.china@gmail.com'
59 | }
60 | }
61 | scm {
62 | connection gitUrl
63 | developerConnection gitUrl
64 | url siteUrl
65 | }
66 | }
67 | }
68 | }
69 | }
70 |
71 | task sourcesJar(type: Jar) {
72 | from android.sourceSets.main.java.srcDirs
73 | classifier = 'sources'
74 | }
75 | task javadoc(type: Javadoc) {
76 | source = android.sourceSets.main.java.srcDirs
77 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
78 | options.encoding = "utf-8" //用来解决javaDoc编码不通过的问题
79 | }
80 | task javadocJar(type: Jar, dependsOn: javadoc) {
81 | classifier = 'javadoc'
82 | from javadoc.destinationDir
83 | }
84 | artifacts {
85 | archives javadocJar
86 | archives sourcesJar
87 | }
88 | Properties properties = new Properties()
89 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
90 | bintray {
91 | user = properties.getProperty("bintray.user")
92 | key = properties.getProperty("bintray.apikey")
93 | configurations = ['archives']
94 | pkg {
95 | repo = "switchview"
96 | name = "switchview" //发布到JCenter上的项目名字
97 | websiteUrl = siteUrl
98 | vcsUrl = gitUrl
99 | licenses = ["Apache-2.0"]
100 | publish = true
101 | }
102 | }
103 |
104 |
--------------------------------------------------------------------------------
/switchview/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Android\AndroidSDK/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/switchview/src/androidTest/java/com/qiangxi/switchview/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.qiangxi.switchview;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.qiangxi.switchview.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/switchview/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/switchview/src/main/java/com/qiangxi/switchview/SwitchView.java:
--------------------------------------------------------------------------------
1 | package com.qiangxi.switchview;
2 |
3 | import android.animation.TimeInterpolator;
4 | import android.content.Context;
5 | import android.content.res.TypedArray;
6 | import android.graphics.Canvas;
7 | import android.graphics.Color;
8 | import android.graphics.Paint;
9 | import android.graphics.PointF;
10 | import android.graphics.RectF;
11 | import android.os.Bundle;
12 | import android.os.Parcelable;
13 | import android.support.annotation.DrawableRes;
14 | import android.support.annotation.Nullable;
15 | import android.util.AttributeSet;
16 | import android.util.TypedValue;
17 | import android.view.Gravity;
18 | import android.view.MotionEvent;
19 | import android.view.animation.LinearInterpolator;
20 | import android.widget.LinearLayout;
21 | import android.widget.TextView;
22 |
23 | import com.qiangxi.switchview.callback.OnItemSelectedListener;
24 |
25 | import java.util.ArrayList;
26 | import java.util.List;
27 | import java.util.TimerTask;
28 |
29 | /**
30 | * @author qiang_xi
31 | */
32 | public class SwitchView extends LinearLayout {
33 | //默认值
34 | private static final int DEFAULT_ITEM_WIDTH = 80;//默认item宽度,单位dp
35 | private static final int DEFAULT_ITEM_HEIGHT = 50;//默认item高度,单位dp
36 | private static final int DEFAULT_TEXT_SIZE = 14;//默认文本大小
37 | private static final int INVALIDATE_POSITION = -1;//无效位置
38 |
39 | //position
40 | private int mLastSelectedPosition = INVALIDATE_POSITION;//滑块所处的上一个位置
41 | private int mSelectedPosition;//滑块所处的当前位置
42 | private int mLockedPosition = INVALIDATE_POSITION;//锁定的位置
43 | //颜色
44 | private int mNormalTextColor;//正常的文字颜色
45 | private int mSelectedTextColor;//选中的文字颜色
46 | private int mSelectedDrawableResId;//选中item的背景drawable id
47 | //字体大小
48 | private float mNormalTextSize;
49 | private float mSelectedTextSize;
50 | //范围
51 | private List mItemBounds = new ArrayList<>();
52 | private List mItemCenterPoint = new ArrayList<>();
53 | //画笔
54 | private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
55 | private Paint mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
56 | //尺寸
57 | private int mItemWidth;
58 | private int mItemHeight;
59 | private int[] mSelectedBgMarginArray = new int[4];//选中的item的背景的margin值,位置对应关系为:int[left,top,right,bottom]
60 | //文本
61 | private String[] mTextArray = {"未知", "休息", "上班", "下班"};
62 |
63 | private int mLastX; //point
64 |
65 | private OnItemSelectedListener mItemSelectedListener;
66 | private TextView mSlideView; //the SlideView
67 | private TimeInterpolator mInterpolator; //插值器
68 | private boolean mScrollEnable = true;//是否禁用滑动手势
69 | private boolean isEnable = true; //是否禁用一切手势,默认不禁用
70 | private boolean isSlideViewPressed;
71 | private boolean isShowText = true;
72 |
73 | public SwitchView(Context context) {
74 | this(context, null);
75 | }
76 |
77 | public SwitchView(Context context, @Nullable AttributeSet attrs) {
78 | this(context, attrs, 0);
79 | }
80 |
81 | public SwitchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
82 | super(context, attrs, defStyleAttr);
83 |
84 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwitchView);
85 | mScrollEnable = a.getBoolean(R.styleable.SwitchView_scrollEnable, true);
86 | isShowText = a.getBoolean(R.styleable.SwitchView_showTextWhenScrolling, true);
87 | mNormalTextColor = a.getColor(R.styleable.SwitchView_normalTextColor, Color.WHITE);
88 | mNormalTextSize = a.getDimensionPixelSize(R.styleable.SwitchView_normalTextSize, DEFAULT_TEXT_SIZE);
89 | mSelectedTextColor = a.getColor(R.styleable.SwitchView_selectedTextColor, Color.RED);
90 | mSelectedTextSize = a.getDimensionPixelSize(R.styleable.SwitchView_selectedTextSize, DEFAULT_TEXT_SIZE);
91 | mSelectedDrawableResId = a.getResourceId(R.styleable.SwitchView_selectedDrawableResId, R.drawable.bg_selected_drawable);
92 | mLockedPosition = a.getInt(R.styleable.SwitchView_lockedPosition, INVALIDATE_POSITION);
93 | CharSequence[] textArray = a.getTextArray(R.styleable.SwitchView_textArray);
94 | mSelectedPosition = mLastSelectedPosition = a.getInt(R.styleable.SwitchView_defaultSelectedPosition, 0);
95 | a.recycle();
96 | convertCharSequenceArrayToStringArray(textArray);
97 | init();
98 | }
99 |
100 | private void generateDefaultSelectedBgMargin() {
101 | mSelectedBgMarginArray[0] = dpToPx(5);
102 | mSelectedBgMarginArray[1] = dpToPx(5);
103 | mSelectedBgMarginArray[2] = dpToPx(5);
104 | mSelectedBgMarginArray[3] = dpToPx(5);
105 | }
106 |
107 | private void convertCharSequenceArrayToStringArray(CharSequence[] array) {
108 | if (array != null) {
109 | mTextArray = null;
110 | mTextArray = new String[array.length];
111 | for (int i = 0; i < array.length; i++) {
112 | mTextArray[i] = array[i].toString();
113 | }
114 | }
115 | }
116 |
117 | private void init() {
118 | mInterpolator = new LinearInterpolator();
119 | mItemWidth = dpToPx(DEFAULT_ITEM_WIDTH);
120 | mItemHeight = dpToPx(DEFAULT_ITEM_HEIGHT);
121 | mTextPaint.setDither(true);
122 | mBgPaint.setDither(true);
123 | generateDefaultSelectedBgMargin();
124 | setupSlideView();
125 | }
126 |
127 | private void setupSlideView() {
128 | mSlideView = null;
129 | removeAllViews();
130 | mSlideView = new TextView(getContext());
131 | setupLayoutParameter(mItemWidth, mItemHeight);
132 | mSlideView.setBackgroundResource(mSelectedDrawableResId);
133 | mSlideView.setTextColor(mSelectedTextColor);
134 | mSlideView.setGravity(Gravity.CENTER);
135 | mSlideView.setTextSize(mSelectedTextSize);
136 | addView(mSlideView);
137 | }
138 |
139 | private int oldItemWidth;
140 | private int oldItemHeight;
141 |
142 | /**
143 | * 增加oldItemWidth,oldItemHeight,用来防止滑动时抖动。
144 | * 抖动的原因:属性动画对采用xBy的方式位移时,每次都会回调onLayout方法,
145 | * 由于在onLayout方法中调用了这个方法,导致每次都会重设SlideView的LayoutParameter,
146 | * 但实际上宽高并没有发生改变,没必要每次都重设SlideView的LayoutParameter,
147 | * 所以添加oldItemWidth,oldItemHeight,用来过滤掉一些非必要的调用,
148 | * 既解决了抖动的问题,又节省了大量性能。
149 | */
150 | private void setupLayoutParameter(int itemWidth, int itemHeight) {
151 | if (oldItemWidth != itemWidth || oldItemHeight != itemHeight) {
152 | int width = itemWidth - mSelectedBgMarginArray[0] - mSelectedBgMarginArray[2];
153 | int height = itemHeight - mSelectedBgMarginArray[1] - mSelectedBgMarginArray[3];
154 | LayoutParams lp = new LayoutParams(width, height);
155 | lp.gravity = Gravity.CENTER_VERTICAL;
156 | lp.leftMargin = mSelectedBgMarginArray[0] + itemWidth * mSelectedPosition;
157 | mSlideView.setLayoutParams(lp);
158 | }
159 | oldItemWidth = itemWidth;
160 | oldItemHeight = itemHeight;
161 | mSlideView.setText(mTextArray[mSelectedPosition]);
162 | }
163 |
164 | /**
165 | * 设置item点击监听
166 | */
167 | public void setOnItemSelectedListener(OnItemSelectedListener listener) {
168 | mItemSelectedListener = listener;
169 | }
170 |
171 | /**
172 | * 设置是否禁用滑动手势
173 | *
174 | * @param scrollEnable true:不禁用,false:禁用,只能点击
175 | */
176 | public void setScrollEnable(boolean scrollEnable) {
177 | mScrollEnable = scrollEnable;
178 | }
179 |
180 | /**
181 | * 平滑移动到指定位置
182 | */
183 | public void smoothScrollTo(int position) {
184 | if (position == INVALIDATE_POSITION) {
185 | return;
186 | }
187 | int rangeDistance = (position - mLastSelectedPosition) * mItemWidth;
188 | moveTo(position, rangeDistance, 200);
189 | }
190 |
191 | /**
192 | * 让SlideView在指定时间内移动指定距离
193 | *
194 | * @param position 移动到的目标位置
195 | * @param scrollDistance 移动的距离
196 | * @param duration 时长
197 | */
198 | private void moveTo(final int position, float scrollDistance, long duration) {
199 | if (!isShowText) {
200 | mSlideView.setText("");
201 | }
202 | if (position != INVALIDATE_POSITION) {
203 | mLastSelectedPosition = position;
204 | }
205 | mSlideView.animate().xBy(scrollDistance).setDuration(duration).setInterpolator(mInterpolator)
206 | .withEndAction(new TimerTask() {
207 | @Override
208 | public void run() {
209 | if (position != INVALIDATE_POSITION && position < mTextArray.length) {
210 | mSlideView.setText(mTextArray[position]);
211 | }
212 | }
213 | });
214 | }
215 |
216 | /**
217 | * 在SlideView滑动的时候是否展示文本
218 | */
219 | public void setShowTextWhenScrolling(boolean isShowText) {
220 | this.isShowText = isShowText;
221 | }
222 |
223 | /**
224 | * 设置插值器
225 | */
226 | public void setInterpolator(TimeInterpolator interpolator) {
227 | if (interpolator == null) {
228 | return;
229 | }
230 | mInterpolator = interpolator;
231 | }
232 |
233 | /**
234 | * 锁定指定位置,锁定之后该位置不可点击和也不能滑动到该位置
235 | */
236 | public void setLockPosition(int position) {
237 | mLockedPosition = position;
238 | }
239 |
240 | /**
241 | * 解锁指定位置
242 | */
243 | public void unlockPosition() {
244 | mLockedPosition = -1;
245 | }
246 |
247 | public int getLockPosition() {
248 | return mLockedPosition;
249 | }
250 |
251 | /**
252 | * 获取item总数量
253 | */
254 | public int getTotalItemCount() {
255 | return mTextArray.length;
256 | }
257 |
258 | /**
259 | * 设置未选中的item的文本颜色
260 | */
261 | public void setNormalTextColor(int normalTextColor) {
262 | mNormalTextColor = normalTextColor;
263 | invalidate();
264 | }
265 |
266 | /**
267 | * 设置选中的item的文本颜色
268 | */
269 | public void setSelectedTextColor(int selectedTextColor) {
270 | mSelectedTextColor = selectedTextColor;
271 | if (mSlideView != null) {
272 | mSlideView.setTextColor(mSelectedTextColor);
273 | }
274 | }
275 |
276 | /**
277 | * 设置选中的item的背景drawable
278 | */
279 | public void setSelectedDrawableResId(@DrawableRes int selectedDrawableResId) {
280 | if (selectedDrawableResId == 0) {
281 | return;
282 | }
283 | mSelectedDrawableResId = selectedDrawableResId;
284 | if (mSlideView != null) {
285 | mSlideView.setBackgroundResource(mSelectedDrawableResId);
286 | }
287 | }
288 |
289 | /**
290 | * 设置未选中的item的字体大小
291 | */
292 | public void setNormalTextSize(float normalTextSize) {
293 | mNormalTextSize = normalTextSize;
294 | invalidate();
295 | }
296 |
297 | /**
298 | * 设置选中的item的字体大小
299 | */
300 | public void setSelectedTextSize(float selectedTextSize) {
301 | mSelectedTextSize = selectedTextSize;
302 | if (mSlideView != null) {
303 | mSlideView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mSelectedTextSize);
304 | }
305 | }
306 |
307 | /**
308 | * 设置选中的item的四周的margin值
309 | *
310 | * @param selectedBgMarginArray 位置关系:int[left,top,right,bottom]
311 | */
312 | public void setSelectedBgMarginArray(int[] selectedBgMarginArray) {
313 | if (selectedBgMarginArray == null || selectedBgMarginArray.length != 4) {
314 | return;
315 | }
316 | mSelectedBgMarginArray = selectedBgMarginArray;
317 | }
318 |
319 | /**
320 | * 该方法用来设置默认选中位置
321 | * 其他需要移动位置的情况请使用{@link #smoothScrollTo(int)}
322 | */
323 | public void setDefaultSelectedPosition(int position) {
324 | mSelectedPosition = position;
325 | setupLayoutParameter(mItemWidth, mItemHeight);
326 | mLastSelectedPosition = position;
327 | }
328 |
329 | /**
330 | * 设置item中填充的文本【运行时不可动态更改】
331 | */
332 | public void setTextArray(String[] textArray) {
333 | if (textArray == null) {
334 | throw new IllegalArgumentException("textArray不可为null");
335 | }
336 | mTextArray = textArray;
337 | }
338 |
339 | /**
340 | * 返回SlideView
341 | *
342 | * @return
343 | */
344 | public TextView getSlideView() {
345 | return mSlideView;
346 | }
347 |
348 | public boolean isEnable() {
349 | return isEnable;
350 | }
351 |
352 | /**
353 | * 是否禁用一切手势
354 | *
355 | * @param enable false:禁用,true不禁用
356 | */
357 | public void setEnable(boolean enable) {
358 | isEnable = enable;
359 | }
360 |
361 | @Override
362 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
363 | super.onMeasure(widthMeasureSpec, heightMeasureSpec);
364 | int widthMode = MeasureSpec.getMode(widthMeasureSpec);
365 | int widthSize = MeasureSpec.getSize(widthMeasureSpec);
366 | int heightMode = MeasureSpec.getMode(heightMeasureSpec);
367 | int heightSize = MeasureSpec.getSize(heightMeasureSpec);
368 |
369 | int width;
370 | int height;
371 | if (widthMode == MeasureSpec.AT_MOST) {
372 | width = mItemWidth * mTextArray.length;
373 | } else {
374 | width = widthSize;
375 | }
376 | if (heightMode == MeasureSpec.AT_MOST) {
377 | height = mItemHeight;
378 | } else {
379 | height = heightSize;
380 | }
381 | setMeasuredDimension(Math.min(width, widthSize), Math.min(height, heightSize));
382 | }
383 |
384 | @Override
385 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
386 | super.onLayout(changed, left, top, right, bottom);
387 | mItemWidth = getWidth() / mTextArray.length;
388 | mItemHeight = getHeight();
389 | setupLayoutParameter(mItemWidth, mItemHeight);
390 | setupItemBoundsAndPoint();
391 | }
392 |
393 | private void setupItemBoundsAndPoint() {
394 | mItemBounds.clear();
395 | mItemCenterPoint.clear();
396 | for (int i = 0; i < mTextArray.length; i++) {
397 | //每个position的范围,用来判断任意点是否在某个范围内
398 | mItemBounds.add(new RectF(i, 0, mItemWidth * (i + 1), mItemHeight));
399 | //每个item的中心点(顶部居中),用来获取手指抬起时,SlideView的顶部中心点与某个item中心点的距离
400 | mItemCenterPoint.add(new PointF(mItemWidth * i + mItemWidth / 2, mSlideView.getY()));
401 | }
402 | }
403 |
404 | @Override
405 | protected void dispatchDraw(Canvas canvas) {
406 | mTextPaint.setColor(mNormalTextColor);
407 | mTextPaint.setTextSize(spToPx(mNormalTextSize));
408 | for (int i = 0; i < mTextArray.length; i++) {
409 | drawText(canvas, i);
410 | }
411 | super.dispatchDraw(canvas);
412 | }
413 |
414 | private void drawText(Canvas canvas, int position) {
415 | String textToDraw = mTextArray[position];
416 | int textWidth = getTextWidth(textToDraw);
417 | canvas.drawText(textToDraw,
418 | (mItemWidth - textWidth) / 2 + mItemWidth * position,
419 | getTextStartY(),
420 | mTextPaint);
421 | }
422 |
423 | @Override
424 | public boolean onTouchEvent(MotionEvent event) {
425 | int action = event.getAction();
426 | switch (action) {
427 | case MotionEvent.ACTION_DOWN:
428 | if (!isEnable) {
429 | return false;
430 | }
431 | mLastX = (int) event.getX();
432 | int lastY = (int) event.getY();
433 | int downPosition = findPositionByPoint(mLastX, lastY);
434 | //判断按下的是否是SlideView
435 | isSlideViewPressed = downPosition == mLastSelectedPosition;
436 | //若按下的是SlideView,则捕获该次事件
437 | if (isSlideViewPressed) {
438 | break;
439 | }
440 | //按下的是被锁定的位置则不处理
441 | if (downPosition == mLockedPosition) {
442 | return false;
443 | }
444 | break;
445 | case MotionEvent.ACTION_MOVE:
446 | if (mScrollEnable && isSlideViewPressed) {
447 | float x = event.getX();
448 | //mSlideView横向滑动范围,在这个范围内都可滑动
449 | if (mSlideView.getX() > 0 && mSlideView.getX() < getWidth() - mItemWidth * 4 / 5) {
450 | float distance = x - mLastX;
451 | moveTo(INVALIDATE_POSITION, distance, 0);
452 | }
453 | mLastX = (int) x;
454 | }
455 | break;
456 | case MotionEvent.ACTION_UP:
457 | int lastSelectedPosition = mLastSelectedPosition;
458 | if (mScrollEnable && isSlideViewPressed) {
459 | float x = mSlideView.getX() + mSlideView.getWidth() / 2;
460 | float y = mSlideView.getY();
461 | int targetPosition = findPositionByPoint(x, y);
462 | //若目标位置是锁定位置,则返回到上一个位置
463 | if (targetPosition == mLockedPosition) {
464 | float distance = calculateDistanceFromCurrentToTarget(x, mLastSelectedPosition);
465 | moveTo(mLastSelectedPosition, distance, 50);
466 | break;
467 | } else {
468 | mSelectedPosition = targetPosition;
469 | float distance = calculateDistanceFromCurrentToTarget(x, mSelectedPosition);
470 | //当前选中位置与上次选中位置是否相等,若相等则只滑动,不触发回调,否则既滑动又触发回调
471 | if (mSelectedPosition == mLastSelectedPosition) {
472 | moveTo(mSelectedPosition, distance, 50);
473 | break;
474 | } else {
475 | moveTo(mSelectedPosition, distance, 50);
476 | }
477 | }
478 | } else if (!isSlideViewPressed) {
479 | float x = event.getX();
480 | float y = event.getY();
481 | int targetPosition = findPositionByPoint(x, y);
482 | //若目标位置是锁定位置,则返回到上一个位置
483 | if (targetPosition == mLockedPosition) {
484 | break;
485 | }
486 | mSelectedPosition = targetPosition;
487 | if (mSelectedPosition == INVALIDATE_POSITION) {
488 | break;
489 | }
490 | if (mSelectedPosition == mLastSelectedPosition) {
491 | break;
492 | }
493 | smoothScrollTo(mSelectedPosition);
494 | }
495 | if (mItemSelectedListener != null) {
496 | mItemSelectedListener.onItemSelected(mSelectedPosition, lastSelectedPosition);
497 | }
498 | break;
499 | }
500 | return true;
501 | }
502 |
503 | /**
504 | * 根据任意点x,y,找到该点对应的position
505 | *
506 | * @param x 给定点的x坐标
507 | * @param y 给定点的x坐标
508 | * @return 给定点对应的position
509 | */
510 | private int findPositionByPoint(float x, float y) {
511 | for (int i = 0; i < mItemBounds.size(); i++) {
512 | if (mItemBounds.get(i).contains(x, y)) {
513 | return i;
514 | }
515 | }
516 | //纠偏,防止数组越界
517 | if (x < mItemBounds.get(0).left) {
518 | return 0;
519 | }
520 | //纠偏,防止数组越界
521 | if (x >= mItemBounds.get(mItemBounds.size() - 1).right) {
522 | return mItemBounds.size() - 1;
523 | }
524 | return INVALIDATE_POSITION;
525 | }
526 |
527 | /**
528 | * 计算手指抬起点到目标点的距离,用于滑动
529 | *
530 | * @param x 给定点的x坐标
531 | * @return 任意点到目标点的距离
532 | * @see #findPositionByPoint(float x, float y);根据该方法查找目标点
533 | */
534 | private float calculateDistanceFromCurrentToTarget(float x, int targetPosition) {
535 | if (targetPosition == INVALIDATE_POSITION) {
536 | return 0;
537 | }
538 | PointF targetCenterPoint = mItemCenterPoint.get(targetPosition);
539 | //计算x方向的差值
540 | return targetCenterPoint.x - x;//>0:右滑,<0:左滑
541 | }
542 |
543 |
544 | @Override
545 | protected Parcelable onSaveInstanceState() {
546 | final Bundle bundle = new Bundle();
547 | bundle.putParcelable("superState", super.onSaveInstanceState());
548 | bundle.putInt("selectedPosition", mSelectedPosition);
549 | bundle.putInt("lastSelectedPosition", mLastSelectedPosition);
550 | bundle.putInt("oldItemWidth", oldItemWidth);
551 | bundle.putInt("oldItemHeight", oldItemHeight);
552 | bundle.putInt("normalTextColor", mNormalTextColor);
553 | bundle.putFloat("normalTextSize", mNormalTextSize);
554 | bundle.putInt("selectedTextColor", mSelectedTextColor);
555 | bundle.putFloat("selectedTextSize", mSelectedTextSize);
556 | bundle.putInt("selectedDrawableRedId", mSelectedDrawableResId);
557 | bundle.putBoolean("scrollEnable", mScrollEnable);
558 | return bundle;
559 | }
560 |
561 | @Override
562 | protected void onRestoreInstanceState(Parcelable state) {
563 | if (state instanceof Bundle) {
564 | Bundle bundle = (Bundle) state;
565 | state = bundle.getParcelable("superState");
566 | mSelectedPosition = bundle.getInt("selectedPosition");
567 | mLastSelectedPosition = bundle.getInt("lastSelectedPosition");
568 | oldItemWidth = bundle.getInt("oldItemWidth");
569 | oldItemHeight = bundle.getInt("oldItemHeight");
570 | mNormalTextColor = bundle.getInt("normalTextColor");
571 | mNormalTextSize = bundle.getFloat("normalTextSize");
572 | mSelectedTextColor = bundle.getInt("selectedTextColor");
573 | mSelectedTextSize = bundle.getFloat("selectedTextSize");
574 | mSelectedDrawableResId = bundle.getInt("selectedDrawableRedId");
575 | mScrollEnable = bundle.getBoolean("scrollEnable");
576 | invalidate();
577 | setupLayoutParameter(mItemWidth, mItemHeight);
578 | if (mSlideView != null) {
579 | mSlideView.setTextColor(mSelectedTextColor);
580 | mSlideView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mSelectedTextSize);
581 | mSlideView.setBackgroundResource(mSelectedDrawableResId);
582 | }
583 | }
584 | super.onRestoreInstanceState(state);
585 | }
586 |
587 | private int dpToPx(int dp) {
588 | float scale = getContext().getResources().getDisplayMetrics().density;
589 | return (int) ((dp * scale) + 0.5f);
590 | }
591 |
592 | private float spToPx(float sp) {
593 | return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
594 | sp, getContext().getResources().getDisplayMetrics());
595 | }
596 |
597 | private int getTextWidth(String text) {
598 | return (int) mTextPaint.measureText(text);
599 | }
600 |
601 | private int getTextStartY() {
602 | Paint.FontMetricsInt fm = mTextPaint.getFontMetricsInt();
603 | return getHeight() / 2 - fm.descent + (fm.descent - fm.ascent) / 2;
604 | }
605 | }
606 |
--------------------------------------------------------------------------------
/switchview/src/main/java/com/qiangxi/switchview/callback/OnItemSelectedListener.java:
--------------------------------------------------------------------------------
1 | package com.qiangxi.switchview.callback;
2 |
3 | /**
4 | * @author qiang_xi
5 | * item选中监听
6 | */
7 | public interface OnItemSelectedListener {
8 |
9 | /**
10 | * @param currentSelectedPosition 当前选中位置
11 | * @param lastSelectedPosition 上次选中位置
12 | */
13 | void onItemSelected(int currentSelectedPosition, int lastSelectedPosition);
14 | }
15 |
--------------------------------------------------------------------------------
/switchview/src/main/res/drawable/bg_selected_drawable.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/switchview/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/switchview/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | switchview
3 |
4 |
--------------------------------------------------------------------------------
/switchview/src/test/java/com/qiangxi/switchview/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.qiangxi.switchview;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------