data) {
28 | mContext = context;
29 | mData = data;
30 | mLayoutInflater = LayoutInflater.from(context);
31 | }
32 |
33 | @Override
34 | public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
35 | View rootView = mLayoutInflater.inflate(R.layout.layout_rv_item_main, parent, false);
36 | RVMainViewHolder holder = new RVMainViewHolder(rootView);
37 | rootView.setOnClickListener(this);
38 | return holder;
39 | }
40 |
41 | @Override
42 | public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
43 | PetInfo tempInfo = mData.get(position);
44 | if (holder instanceof RVMainViewHolder) {
45 | RVMainViewHolder mainHolder = (RVMainViewHolder) holder;
46 | mainHolder.tvTitle.setText(tempInfo.getName());
47 | mainHolder.tvDescription.setText(tempInfo.getDescription());
48 | mainHolder.swSelect.setChecked(tempInfo.isSelected());
49 | mainHolder.swSelect.setTag(tempInfo.getPicId());
50 | mainHolder.swSelect.setOnCheckedChangeListener(this);
51 | mainHolder.ivItemPic.setScaleType(ImageView.ScaleType.CENTER_CROP);
52 | mainHolder.ivItemPic.setBackgroundResource(tempInfo.getPicId());
53 |
54 | holder.itemView.setTag(mData.get(position));
55 | }
56 | }
57 |
58 | @Override
59 | public int getItemCount() {
60 | return mData.size();
61 | }
62 |
63 | @Override
64 | public void onClick(View v) {
65 | if (mOnItemClickListener != null) {
66 | mOnItemClickListener.onItemClick(v, (PetInfo) v.getTag());
67 | }
68 | }
69 |
70 | private OnRvItemClickListener mOnItemClickListener = null;
71 | private OnPetSelectedListener mSelectedListener = null;
72 |
73 | @Override
74 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
75 | if (mSelectedListener != null) {
76 | mSelectedListener.onPetSelected(buttonView, (Integer) buttonView.getTag());
77 | }
78 | }
79 |
80 | public static interface OnRvItemClickListener {
81 | void onItemClick(View view, PetInfo petInfo);
82 | }
83 |
84 | public static interface OnPetSelectedListener {
85 | void onPetSelected(CompoundButton buttonView, int petId);
86 | }
87 |
88 | public void setOnPetSelectedListener(OnPetSelectedListener listener) {
89 | mSelectedListener = listener;
90 | }
91 |
92 | public void setOnRvItemClickListener(OnRvItemClickListener listener) {
93 | mOnItemClickListener = listener;
94 | }
95 |
96 | public void swapData(int fromPosition, int toPosition) {
97 | if (fromPosition < toPosition) {
98 | for (int i = fromPosition; i < toPosition; i++) {
99 | Collections.swap(mData, i, i + 1);
100 | }
101 | } else {
102 | for (int i = fromPosition; i > toPosition; i--) {
103 | Collections.swap(mData, i, i - 1);
104 | }
105 | }
106 | notifyItemMoved(fromPosition, toPosition);
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/app/src/main/java/com/rdc/goospet/swipeback/Utils.java:
--------------------------------------------------------------------------------
1 |
2 | package com.rdc.goospet.swipeback;
3 |
4 | import android.app.Activity;
5 | import android.app.ActivityOptions;
6 | import android.os.Build;
7 |
8 | import java.lang.reflect.Method;
9 |
10 | public class Utils {
11 | private Utils() {
12 | }
13 |
14 | /**
15 | * Convert a translucent themed Activity
16 | * {@link android.R.attr#windowIsTranslucent} to a fullscreen opaque
17 | * Activity.
18 | *
19 | * Call this whenever the background of a translucent Activity has changed
20 | * to become opaque. Doing so will allow the {@link android.view.Surface} of
21 | * the Activity behind to be released.
22 | *
23 | * This call has no effect on non-translucent activities or on activities
24 | * with the {@link android.R.attr#windowIsFloating} attribute.
25 | */
26 | public static void convertActivityFromTranslucent(Activity activity) {
27 | try {
28 | Method method = Activity.class.getDeclaredMethod("convertFromTranslucent");
29 | method.setAccessible(true);
30 | method.invoke(activity);
31 | } catch (Throwable t) {
32 | }
33 | }
34 |
35 | /**
36 | * Convert a translucent themed Activity
37 | * {@link android.R.attr#windowIsTranslucent} back from opaque to
38 | * translucent following a call to
39 | * {@link #convertActivityFromTranslucent(Activity)} .
40 | *
41 | * Calling this allows the Activity behind this one to be seen again. Once
42 | * all such Activities have been redrawn
43 | *
44 | * This call has no effect on non-translucent activities or on activities
45 | * with the {@link android.R.attr#windowIsFloating} attribute.
46 | */
47 | public static void convertActivityToTranslucent(Activity activity) {
48 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
49 | convertActivityToTranslucentAfterL(activity);
50 | } else {
51 | convertActivityToTranslucentBeforeL(activity);
52 | }
53 | }
54 |
55 | /**
56 | * Calling the convertToTranslucent method on platforms before Android 5.0
57 | */
58 | public static void convertActivityToTranslucentBeforeL(Activity activity) {
59 | try {
60 | Class>[] classes = Activity.class.getDeclaredClasses();
61 | Class> translucentConversionListenerClazz = null;
62 | for (Class clazz : classes) {
63 | if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
64 | translucentConversionListenerClazz = clazz;
65 | }
66 | }
67 | Method method = Activity.class.getDeclaredMethod("convertToTranslucent",
68 | translucentConversionListenerClazz);
69 | method.setAccessible(true);
70 | method.invoke(activity, new Object[] {
71 | null
72 | });
73 | } catch (Throwable t) {
74 | }
75 | }
76 |
77 | /**
78 | * Calling the convertToTranslucent method on platforms after Android 5.0
79 | */
80 | private static void convertActivityToTranslucentAfterL(Activity activity) {
81 | try {
82 | Method getActivityOptions = Activity.class.getDeclaredMethod("getActivityOptions");
83 | getActivityOptions.setAccessible(true);
84 | Object options = getActivityOptions.invoke(activity);
85 |
86 | Class>[] classes = Activity.class.getDeclaredClasses();
87 | Class> translucentConversionListenerClazz = null;
88 | for (Class clazz : classes) {
89 | if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
90 | translucentConversionListenerClazz = clazz;
91 | }
92 | }
93 | Method convertToTranslucent = Activity.class.getDeclaredMethod("convertToTranslucent",
94 | translucentConversionListenerClazz, ActivityOptions.class);
95 | convertToTranslucent.setAccessible(true);
96 | convertToTranslucent.invoke(activity, null, options);
97 | } catch (Throwable t) {
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/app/src/main/java/com/rdc/goospet/view/activity/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.rdc.goospet.view.activity;
2 |
3 | import android.content.Intent;
4 | import android.support.constraint.ConstraintLayout;
5 | import android.support.design.widget.FloatingActionButton;
6 | import android.support.v7.widget.LinearLayoutManager;
7 | import android.support.v7.widget.RecyclerView;
8 | import android.support.v7.widget.helper.ItemTouchHelper;
9 | import android.view.View;
10 | import android.view.animation.AccelerateInterpolator;
11 | import android.view.animation.DecelerateInterpolator;
12 |
13 | import com.rdc.goospet.R;
14 | import com.rdc.goospet.adapter.RVMainAdapter;
15 | import com.rdc.goospet.base.BaseActivity;
16 | import com.rdc.goospet.listener.HidingScrollListener;
17 | import com.rdc.goospet.presenter.MainPresenter;
18 | import com.rdc.goospet.service.FloatingPetService;
19 | import com.rdc.goospet.utils.DimenUtils;
20 | import com.rdc.goospet.view.vinterface.MainVInterface;
21 |
22 | /**
23 | * 主界面
24 | */
25 | public class MainActivity extends BaseActivity implements MainVInterface, View.OnClickListener {
26 |
27 |
28 | private RecyclerView mRvMain;
29 | private FloatingActionButton mFABSetting;
30 |
31 | @Override
32 | protected MainPresenter createPresenter() {
33 | return new MainPresenter(this);
34 | }
35 |
36 | @Override
37 | protected int setContentViewById() {
38 | return R.layout.activity_main;
39 | }
40 |
41 | @Override
42 | protected void initAttributes() {
43 |
44 | }
45 |
46 | @Override
47 | protected void initView() {
48 | findAllViewById();
49 | initRv();
50 | mFABSetting.setOnClickListener(this);
51 | }
52 |
53 | /**
54 | * 加载R
55 | */
56 | private void initRv() {
57 | RVMainAdapter rvAdapter = mPresenter.getRVAdapter(this);
58 | mRvMain.setLayoutManager(new LinearLayoutManager(this));
59 | mRvMain.setAdapter(rvAdapter);
60 | mRvMain.addOnScrollListener(new HidingScrollListener() {
61 | @Override
62 | public void onHide() {
63 | hideFAB();
64 | }
65 |
66 | @Override
67 | public void onShow() {
68 | showFAB();
69 | }
70 | });
71 | ItemTouchHelper itemHelper = mPresenter.getItemTouchHelper(rvAdapter);
72 | itemHelper.attachToRecyclerView(mRvMain);
73 | }
74 |
75 |
76 | /**
77 | * 显示悬浮按钮
78 | */
79 | private void showFAB() {
80 | mFABSetting.animate().translationY(0).setInterpolator(new DecelerateInterpolator(1)).start();
81 | }
82 |
83 | /**
84 | * 隐藏悬浮按钮
85 | */
86 | private void hideFAB() {
87 | ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) mFABSetting.getLayoutParams();
88 | int fabBottomMargin = lp.bottomMargin;
89 | mFABSetting.animate().translationY(mFABSetting.getHeight() + fabBottomMargin + DimenUtils.getNavBarHeight(this) + DimenUtils.getStatusBarHeight(this)).
90 | setInterpolator(new AccelerateInterpolator(2)).start();
91 | }
92 |
93 |
94 | @Override
95 | protected void findAllViewById() {
96 | mRvMain = $(R.id.rv_main);
97 | mFABSetting = $(R.id.fab_setting);
98 | }
99 |
100 | @Override
101 | public void onClick(View view) {
102 | switch (view.getId()) {
103 | case R.id.rv_main:
104 | break;
105 | case R.id.fab_setting:
106 | Intent intent = new Intent(MainActivity.this, SettingActivity.class);
107 | startActivityWithAnim(intent);
108 | break;
109 | // case R.id.btn_show:
110 | // //启动悬浮pet
111 | // Intent intent = new Intent(MainActivity.this, FloatingPetService.class);
112 | // startService(intent);
113 | // Intent home = new Intent(Intent.ACTION_MAIN);
114 | // home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
115 | // home.addCategory(Intent.CATEGORY_HOME);
116 | // startActivity(home);
117 | // break;
118 | }
119 | }
120 |
121 | @Override
122 | protected void onDestroy() {
123 | // stopService();
124 | super.onDestroy();
125 | }
126 |
127 | @Override
128 | public void launchDesktopPet() {
129 | //启动悬浮pet
130 | Intent intent = new Intent(MainActivity.this, FloatingPetService.class);
131 | startService(intent);
132 | Intent home = new Intent(Intent.ACTION_MAIN);
133 | home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
134 | home.addCategory(Intent.CATEGORY_HOME);
135 | startActivity(home);
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/java/com/rdc/goospet/base/BaseActivity.java:
--------------------------------------------------------------------------------
1 | package com.rdc.goospet.base;
2 |
3 | import android.app.ProgressDialog;
4 | import android.content.Intent;
5 | import android.os.Build;
6 | import android.os.Bundle;
7 | import android.support.v7.app.AppCompatActivity;
8 | import android.support.v7.widget.Toolbar;
9 | import android.view.View;
10 |
11 | import com.rdc.goospet.R;
12 | import com.rdc.goospet.utils.AppConstants;
13 | import com.rdc.goospet.utils.DimenUtils;
14 |
15 | /**
16 | * Created by Goo on 2016-8-28.
17 | */
18 | public abstract class BaseActivity> extends AppCompatActivity {
19 | protected Toolbar toolbar;
20 | protected P mPresenter;
21 | private ProgressDialog mProgressDialog;
22 |
23 |
24 | @Override
25 | public void onCreate(Bundle savedInstanceState) {
26 | super.onCreate(savedInstanceState);
27 | setContentView(setContentViewById());
28 | //创建Presenter,并把自己交给Present
29 | mPresenter = createPresenter();
30 | mPresenter.attachView((V) this);
31 | initAttributes();
32 | initView();
33 | }
34 |
35 | //获取Presenter;
36 | protected abstract P createPresenter();
37 |
38 | protected abstract int setContentViewById();
39 |
40 | protected abstract void initAttributes();
41 |
42 | protected abstract void initView();
43 |
44 | protected abstract void findAllViewById();
45 |
46 | /**
47 | * @param title 直接显示返回箭头的toolbar
48 | */
49 | public void showToolbarAndShowNavigation(String title) {
50 | toolbar = (Toolbar) findViewById(R.id.toolbar);
51 | setToolbarTitle(title);
52 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
53 | toolbar.getLayoutParams().height = DimenUtils.getAppBarHeight(this);
54 | toolbar.setPadding(toolbar.getPaddingLeft(),
55 | DimenUtils.getStatusBarHeight(this),
56 | toolbar.getPaddingRight(),
57 | toolbar.getPaddingBottom());
58 | }
59 | showToolBar();
60 | showOrHideToolBarNavigation(true);
61 | }
62 |
63 |
64 | /**
65 | * 设置toolbar标题
66 | *
67 | * @param title
68 | */
69 | private void setToolbarTitle(String title) {
70 | if (toolbar != null) {
71 | toolbar.setTitle(title);
72 | toolbar.setTitleTextColor(0xFFFFFFFF);
73 | }
74 | }
75 |
76 | /**
77 | * 显示ToolBar
78 | */
79 | private void showToolBar() {
80 | if (toolbar != null) {
81 | setSupportActionBar(toolbar);
82 | }
83 | if (getSupportActionBar() != null) {
84 | getSupportActionBar().show();
85 | }
86 | }
87 |
88 | /**
89 | * 是否隐藏ToolBar返回按钮
90 | *
91 | * @param show
92 | */
93 | public void showOrHideToolBarNavigation(boolean show) {
94 | if (show) {
95 | //设置返回键
96 | if (getSupportActionBar() != null) {
97 | getSupportActionBar().setDisplayHomeAsUpEnabled(true);
98 | }
99 | toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
100 | toolbar.setNavigationOnClickListener(new View.OnClickListener() {
101 | @Override
102 | public void onClick(View v) {
103 | finish();
104 | setPendingTransition(AppConstants.OUT_PENDING_TRANSITION);
105 | }
106 | });
107 | }
108 | }
109 |
110 | /**
111 | * Activity切换动画
112 | *
113 | * @param TYPE
114 | */
115 | public void setPendingTransition(int TYPE) {
116 | if (TYPE == AppConstants.OPEN_PENDING_TRANSITION) {
117 | overridePendingTransition(R.anim.transition_right_in,
118 | R.anim.transition_not_move);
119 | } else if (TYPE == AppConstants.OUT_PENDING_TRANSITION) {
120 | overridePendingTransition(R.anim.transition_not_move,
121 | R.anim.transition_right_out);
122 | }
123 | }
124 |
125 | /**
126 | * 启动Activity
127 | *
128 | * @param clazz
129 | */
130 | protected void launchActivity(Class clazz) {
131 | Intent intent = new Intent(this, clazz);
132 | startActivity(intent);
133 | }
134 |
135 | /**
136 | * 启动Activity - 有启动码
137 | *
138 | * @param clazz
139 | * @param requestCode
140 | */
141 | protected void launchActivity(Class clazz, int requestCode) {
142 | Intent intent = new Intent(this, clazz);
143 | startActivityForResult(intent, requestCode);
144 | }
145 |
146 | /**
147 | * 替换 findViewById
148 | *
149 | * @param viewId
150 | * @param
151 | * @return
152 | */
153 | protected T $(int viewId) {
154 | return (T) findViewById(viewId);
155 | }
156 |
157 |
158 | protected void showProgressDialog(String msg) {
159 | if (mProgressDialog == null)
160 | mProgressDialog = new ProgressDialog(this);
161 | mProgressDialog.setMessage(msg);
162 | //可取消
163 | mProgressDialog.setCancelable(true);
164 | //不显示进度
165 | mProgressDialog.setIndeterminate(false);
166 | mProgressDialog.show();
167 | }
168 |
169 | protected void dismissProgressDialog() {
170 | if (mProgressDialog != null && mProgressDialog.isShowing())
171 | mProgressDialog.dismiss();
172 | }
173 |
174 | /**
175 | * 带动画启动Activity
176 | *
177 | * @param intent
178 | */
179 | protected void startActivityWithAnim(Intent intent) {
180 | startActivity(intent);
181 | setPendingTransition(AppConstants.OPEN_PENDING_TRANSITION);
182 | }
183 |
184 | /**
185 | * 带动画关闭Activity
186 | */
187 | protected void finishActivityWithAnim() {
188 | finish();
189 | setPendingTransition(AppConstants.OUT_PENDING_TRANSITION);
190 | }
191 |
192 |
193 | }
194 |
--------------------------------------------------------------------------------
/app/src/main/res/values/vpi__attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
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 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
--------------------------------------------------------------------------------
/app/src/main/java/com/rdc/goospet/view/widget/FloatingPetView.java:
--------------------------------------------------------------------------------
1 | package com.rdc.goospet.view.widget;
2 |
3 | import android.animation.ValueAnimator;
4 | import android.content.Context;
5 | import android.util.DisplayMetrics;
6 | import android.view.LayoutInflater;
7 | import android.view.MotionEvent;
8 | import android.view.View;
9 | import android.view.WindowManager;
10 | import android.widget.ImageView;
11 | import android.widget.LinearLayout;
12 |
13 | import com.rdc.goospet.R;
14 | import com.rdc.goospet.utils.FloatingUtils;
15 | import com.rdc.goospet.utils.LogUtils;
16 |
17 | import java.util.Random;
18 |
19 | /**
20 | * Created by Goo on 2016-9-18.
21 | */
22 | public class FloatingPetView extends LinearLayout {
23 | /**
24 | * 窗体宽高
25 | */
26 | public static int viewWidth, viewHeight;
27 |
28 | /**
29 | * 系统状态栏高度
30 | */
31 | private static int statusBarHeight;
32 |
33 | /**
34 | * 屏幕宽高
35 | */
36 | private int screenHeight, screenWidth;
37 |
38 | /**
39 | * 窗体管理
40 | */
41 | private WindowManager mWindowManager;
42 | private WindowManager.LayoutParams mParams;
43 |
44 | /**
45 | * 悬浮窗Iv
46 | */
47 | private ImageView mIvPet;
48 |
49 | /**
50 | * 位置参数
51 | */
52 | private float xInView, yInView, xDownInScreen, yDownInScreen, xInScreen, yInScreen;
53 |
54 | /**
55 | * 是否按住状态
56 | */
57 | private boolean isPressed = false;
58 |
59 | /**
60 | * 是否需要隐藏
61 | */
62 | private boolean isNeedHide = false;
63 |
64 | /**
65 | * 动画 - 按住状态
66 | */
67 | private ValueAnimator mTouchedAnim;
68 |
69 | /**
70 | * 动画 - 移动状态
71 | */
72 | private ValueAnimator mMovingAnim;
73 |
74 |
75 | public FloatingPetView(Context context) {
76 | super(context);
77 | initView(context);
78 | }
79 |
80 | /**
81 | * 初始化视图
82 | *
83 | * @param context
84 | */
85 | private void initView(Context context) {
86 | LayoutInflater.from(context).inflate(R.layout.layout_widget_pet, this);
87 | findAllViewById();
88 | initViewParams(context);
89 | defaultPetStatus();
90 | }
91 |
92 | private void findAllViewById() {
93 | mIvPet = (ImageView) findViewById(R.id.iv_pet);
94 | }
95 |
96 | /**
97 | * 初始化窗体宽高参数
98 | */
99 | private void initViewParams(Context context) {
100 | View view = findViewById(R.id.ll_pet);
101 | viewWidth = view.getLayoutParams().width;
102 | viewHeight = view.getLayoutParams().height;
103 | DisplayMetrics dm = new DisplayMetrics();
104 | mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
105 | mWindowManager.getDefaultDisplay().getMetrics(dm);
106 | statusBarHeight = FloatingUtils.getStatusBarHeight(this);
107 | if (statusBarHeight != -1) {
108 | screenWidth = dm.widthPixels;
109 | screenHeight = dm.heightPixels - statusBarHeight;
110 | } else {
111 | LogUtils.e("statusBarHeight = -1");
112 | }
113 | }
114 |
115 | /**
116 | * 设置宠物样式
117 | *
118 | * @param resid
119 | */
120 | private void setPetImg(int resid) {
121 | mIvPet.setBackgroundResource(resid);
122 | }
123 |
124 | /**
125 | * 将小悬浮窗的参数传入,用于更新小悬浮窗的位置。
126 | *
127 | * @param params 小悬浮窗的参数
128 | */
129 | public void setParams(WindowManager.LayoutParams params) {
130 | mParams = params;
131 | }
132 |
133 | /**
134 | * 处理控件触摸事件
135 | *
136 | * @param event
137 | * @return
138 | */
139 | @Override
140 | public boolean onTouchEvent(MotionEvent event) {
141 | switch (event.getAction()) {
142 | case MotionEvent.ACTION_DOWN:
143 | isPressed = true;
144 | refreshParamsForDown(event);
145 | updatePetState();
146 | break;
147 | case MotionEvent.ACTION_MOVE:
148 | isNeedHide = false;
149 | refreshParamsForMove(event);
150 | updatePetPosition();
151 | updatePetState();
152 | break;
153 | case MotionEvent.ACTION_UP:
154 | isPressed = false;
155 |
156 | if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
157 | //触摸坐标不变,即点击事件
158 | updatePetState();
159 | } else if (xInScreen < screenWidth / 8) { //当在这个位置放手时宠物贴边隐藏
160 | hideLeft();
161 | } else if (xInScreen > screenWidth * 7 / 8) {
162 | hideRight();
163 | break;
164 | } else {
165 | updatePetState();
166 | }
167 | }
168 | return true;
169 | }
170 |
171 | /**
172 | * 右边贴边
173 | */
174 | private void hideRight() {
175 | setPetImg(R.drawable.ic_pet_hide_right);
176 | }
177 |
178 | /**
179 | * 左边贴边
180 | */
181 | private void hideLeft() {
182 | setPetImg(R.drawable.ic_pet_hide_left);
183 | }
184 |
185 | /**
186 | * 更新宠物状态
187 | */
188 | private void updatePetState() {
189 | if (isPressed) {
190 | //按住状态
191 | touchPetStatus();
192 | } else if (isNeedHide) {
193 | //没有按住,需要贴边,贴边即可
194 | } else {
195 | //没有按住,也不需要贴边,默认状态即可
196 | defaultPetStatus();
197 | }
198 | }
199 |
200 | private void defaultPetStatus() {
201 | switch (new Random().nextInt(5) + 3) {
202 | case 3:
203 | setPetImg(R.drawable.ic_face_03);
204 | break;
205 | case 4:
206 | setPetImg(R.drawable.ic_face_04);
207 | break;
208 | case 5:
209 | setPetImg(R.drawable.ic_face_05);
210 | break;
211 | case 6:
212 | setPetImg(R.drawable.ic_face_06);
213 | break;
214 | case 7:
215 | setPetImg(R.drawable.ic_face_07);
216 | break;
217 | }
218 | }
219 |
220 | /**
221 | * 按住(拎起)状态,随机更换表情
222 | */
223 | private void touchPetStatus() {
224 | setPetImg(R.drawable.ic_face_02);
225 | }
226 |
227 | /**
228 | * 更新参数 - 移动时刻
229 | *
230 | * @param event
231 | */
232 | private void refreshParamsForMove(MotionEvent event) {
233 | xInScreen = event.getRawX();
234 | yInScreen = event.getRawY() - FloatingUtils.getStatusBarHeight(this);
235 | }
236 |
237 | /**
238 | * 更新参数 - 按下时刻
239 | *
240 | * @param event
241 | */
242 | private void refreshParamsForDown(MotionEvent event) {
243 | xInView = event.getX();
244 | yInView = event.getY();
245 | xDownInScreen = event.getRawX();
246 | yDownInScreen = event.getRawY() - FloatingUtils.getStatusBarHeight(this);
247 | refreshParamsForMove(event);
248 | }
249 |
250 | /**
251 | * 更新小悬浮窗在屏幕中的位置。
252 | */
253 | private void updatePetPosition() {
254 | mParams.x = (int) (xInScreen - xInView);
255 | mParams.y = (int) (yInScreen - yInView);
256 | mWindowManager.updateViewLayout(this, mParams);
257 | }
258 | }
259 |
--------------------------------------------------------------------------------
/app/src/main/java/com/rdc/goospet/view/activity/IntroActivity.java:
--------------------------------------------------------------------------------
1 | package com.rdc.goospet.view.activity;
2 |
3 | import android.content.Intent;
4 | import android.support.v4.view.ViewPager;
5 | import android.support.v7.app.AlertDialog;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 | import android.widget.EditText;
10 | import android.widget.MaterialEditText;
11 | import android.widget.TextSwitcher;
12 | import android.widget.TextView;
13 |
14 | import com.rdc.goospet.R;
15 | import com.rdc.goospet.adapter.IntroFragmentAdapter;
16 | import com.rdc.goospet.base.BaseActivity;
17 | import com.rdc.goospet.listener.IntroPageChangedListener;
18 | import com.rdc.goospet.presenter.IntroPresenter;
19 | import com.rdc.goospet.utils.AppConstants;
20 | import com.rdc.goospet.utils.DialogUtils;
21 | import com.rdc.goospet.utils.ToastUtil;
22 | import com.rdc.goospet.view.vinterface.IntroVInterface;
23 | import com.rdc.goospet.view.widget.CirclePageIndicator;
24 |
25 | /**
26 | * Created by Goo on 2016-8-28.
27 | * 介绍界面(界面设计暂定)
28 | */
29 | public class IntroActivity extends BaseActivity implements IntroVInterface, View.OnClickListener {
30 |
31 | private ViewPager mVpIntro;
32 | private CirclePageIndicator mIndicator;
33 | private IntroFragmentAdapter mPagerAdapter;
34 |
35 | private TextView mTvIntroLogin, mTvIntroRegister;
36 | private TextView mTvLogin, mTvSocialLogin, mTvRegister;
37 | private TextSwitcher mTSwitcher;
38 |
39 | private EditText mEtAccount, mEtPsw, mEtRAccount, mEtREmail, mEtRPsw, mEtRPswAgain;
40 |
41 | private AlertDialog mLoginDialog, mRegisterDialog = null;
42 |
43 |
44 | @Override
45 | protected IntroPresenter createPresenter() {
46 | return new IntroPresenter(this);
47 | }
48 |
49 |
50 | @Override
51 | protected int setContentViewById() {
52 | return R.layout.activity_intro;
53 | }
54 |
55 | @Override
56 | protected void initAttributes() {
57 |
58 | }
59 |
60 | @Override
61 | protected void initView() {
62 | findAllViewById();
63 | setAllClickListener();
64 | initVp();
65 | initIndicator();
66 | }
67 |
68 | private void initVp() {
69 | mPagerAdapter = mPresenter.getPagerAdapter(getSupportFragmentManager());
70 | mVpIntro.setOffscreenPageLimit(0);
71 | mVpIntro.setAdapter(mPagerAdapter);
72 | mVpIntro.setPageTransformer(true, mPresenter.getTransformer());
73 | }
74 |
75 | private void initIndicator() {
76 | mIndicator.setViewPager(mVpIntro);
77 | mIndicator.setPageColor(getResources().getColor(R.color.standardWhite));
78 | mIndicator.setFillColor(getResources().getColor(R.color.colorAccent));
79 | mIndicator.setOnPageChangeListener(new IntroPageChangedListener(mVpIntro, mTSwitcher, getWindowManager().getDefaultDisplay().getWidth(), mPagerAdapter.getCount(), getResources()));
80 | }
81 |
82 | private void setAllClickListener() {
83 | mTvIntroLogin.setOnClickListener(this);
84 | mTvIntroRegister.setOnClickListener(this);
85 | }
86 |
87 | @Override
88 | protected void findAllViewById() {
89 | mVpIntro = $(R.id.vp_intro);
90 | mIndicator = $(R.id.cpi);
91 | mTvIntroLogin = $(R.id.tv_intro_login);
92 | mTvIntroRegister = $(R.id.tv_intro_register);
93 | mTSwitcher = $(R.id.ts_intro);
94 | }
95 |
96 | @Override
97 | public void onClick(View view) {
98 | switch (view.getId()) {
99 | case R.id.tv_intro_login:
100 | showLoginDialog();
101 | break;
102 | case R.id.tv_intro_register:
103 | showRegisterDialog();
104 | break;
105 | case R.id.tv_login:
106 | dismissDialog();
107 | mPresenter.login(mEtAccount.getText().toString(), mEtPsw.getText().toString());
108 | break;
109 | case R.id.tv_social_login:
110 | break;
111 | case R.id.tv_register:
112 | mPresenter.register(mEtRAccount.getText().toString(), mEtREmail.getText().toString(), mEtRPsw.getText().toString(), mEtRPswAgain.getText().toString());
113 | break;
114 | }
115 | }
116 |
117 |
118 | private void showLoginDialog() {
119 | LayoutInflater inflater = getLayoutInflater();
120 | View loginDialog = inflater.inflate(R.layout.layout_dialog_login, (ViewGroup) findViewById(R.id.ll_dialog));
121 |
122 | mEtAccount = (MaterialEditText) loginDialog.findViewById(R.id.et_account);
123 | mEtPsw = (MaterialEditText) loginDialog.findViewById(R.id.et_psw);
124 | mTvLogin = (TextView) loginDialog.findViewById(R.id.tv_login);
125 | mTvSocialLogin = (TextView) loginDialog.findViewById(R.id.tv_social_login);
126 | mTvLogin.setOnClickListener(this);
127 | mTvSocialLogin.setOnClickListener(this);
128 |
129 | mLoginDialog = DialogUtils.showCoustomDialog(this, loginDialog, "登录");
130 |
131 | }
132 |
133 | private void showRegisterDialog() {
134 |
135 | LayoutInflater inflater = getLayoutInflater();
136 | View registerDialog = inflater.inflate(R.layout.layout_dialog_register, (ViewGroup) findViewById(R.id.ll_dialog));
137 |
138 | mTvRegister = (TextView) registerDialog.findViewById(R.id.tv_register);
139 | mEtRAccount = (EditText) registerDialog.findViewById(R.id.et_register_account);
140 | mEtREmail = (EditText) registerDialog.findViewById(R.id.et_register_email);
141 | mEtRPsw = (EditText) registerDialog.findViewById(R.id.et_register_psw);
142 | mEtRPswAgain = (EditText) registerDialog.findViewById(R.id.et_register_psw_again);
143 | mTvRegister.setOnClickListener(this);
144 |
145 | mRegisterDialog = DialogUtils.showCoustomDialog(this, registerDialog, "注册");
146 | }
147 |
148 | @Override
149 | public void showProgressDialog() {
150 | super.showProgressDialog(getString(R.string.tips_net_working));
151 | }
152 |
153 | @Override
154 | public void dismissDialog() {
155 | super.dismissProgressDialog();
156 | }
157 |
158 | @Override
159 | public void registerSuccess(String userName) {
160 | ToastUtil.showToast(this, getString(R.string.tips_register_success));
161 | EnterMain(userName);
162 |
163 | }
164 |
165 | @Override
166 | public void loginSuccess(String userName) {
167 | EnterMain(userName);
168 | }
169 |
170 | @Override
171 | public void errorLoginFail() {
172 | ToastUtil.showToast(this, getString(R.string.tips_error_login));
173 | }
174 |
175 | @Override
176 | public void errorEmptyInfo() {
177 | ToastUtil.showToast(this, getString(R.string.error_empty_info));
178 | }
179 |
180 | @Override
181 | public void errorPswNotEqual() {
182 | ToastUtil.showToast(this, getString(R.string.error_psw_not_equal));
183 | }
184 |
185 | @Override
186 | public void errorEmailInvalid() {
187 | ToastUtil.showToast(this, getString(R.string.error_email_invalid));
188 | }
189 |
190 | @Override
191 | public void errorUserNameRepeat() {
192 | ToastUtil.showToast(this, getString(R.string.error_username_repeat));
193 |
194 | }
195 |
196 | @Override
197 | public void errorEmailRepeat() {
198 | ToastUtil.showToast(this, getString(R.string.error_email_repeat));
199 | }
200 |
201 | @Override
202 | public void errorNetWork() {
203 | ToastUtil.showToast(this, getString(R.string.error_network));
204 | }
205 |
206 | /**
207 | * 进入主界面
208 | *
209 | * @param userName
210 | */
211 | private void EnterMain(String userName) {
212 | AppConstants.USER_NAME = userName;
213 | Intent intent = new Intent(IntroActivity.this, MainActivity.class);
214 | startActivityWithAnim(intent);
215 | finish();
216 | }
217 |
218 | @Override
219 | protected void onDestroy() {
220 | if (mLoginDialog != null) {
221 | mLoginDialog.dismiss();
222 | }
223 | if (mRegisterDialog != null) {
224 | mRegisterDialog.dismiss();
225 | }
226 | super.onDestroy();
227 | }
228 | }
229 |
--------------------------------------------------------------------------------
/app/src/main/java/com/rdc/goospet/view/widget/CirclePageIndicator.java:
--------------------------------------------------------------------------------
1 | package com.rdc.goospet.view.widget;
2 |
3 | import android.content.Context;
4 | import android.content.res.Resources;
5 | import android.content.res.TypedArray;
6 | import android.graphics.Canvas;
7 | import android.graphics.Paint;
8 | import android.graphics.drawable.Drawable;
9 | import android.os.Parcel;
10 | import android.os.Parcelable;
11 | import android.support.v4.view.MotionEventCompat;
12 | import android.support.v4.view.ViewConfigurationCompat;
13 | import android.support.v4.view.ViewPager;
14 | import android.util.AttributeSet;
15 | import android.view.MotionEvent;
16 | import android.view.View;
17 | import android.view.ViewConfiguration;
18 |
19 | import com.rdc.goospet.R;
20 |
21 | import static android.graphics.Paint.ANTI_ALIAS_FLAG;
22 | import static android.widget.LinearLayout.HORIZONTAL;
23 | import static android.widget.LinearLayout.VERTICAL;
24 |
25 | /**
26 | * from Android ViewPagerIndicator
27 | *
28 | * Created by Goo on 2016-8-31.
29 | */
30 | public class CirclePageIndicator extends View implements PageIndicator {
31 | private static final int INVALID_POINTER = -1;
32 |
33 | private float mRadius;
34 | private final Paint mPaintPageFill = new Paint(ANTI_ALIAS_FLAG);
35 | private final Paint mPaintStroke = new Paint(ANTI_ALIAS_FLAG);
36 | private final Paint mPaintFill = new Paint(ANTI_ALIAS_FLAG);
37 | private ViewPager mViewPager;
38 | private ViewPager.OnPageChangeListener mListener;
39 | private int mCurrentPage;
40 | private int mSnapPage;
41 | private float mPageOffset;
42 | private int mScrollState;
43 | private int mOrientation;
44 | private boolean mCentered;
45 | private boolean mSnap;
46 |
47 | private int mTouchSlop;
48 | private float mLastMotionX = -1;
49 | private int mActivePointerId = INVALID_POINTER;
50 | private boolean mIsDragging;
51 |
52 |
53 | public CirclePageIndicator(Context context) {
54 | this(context, null);
55 | }
56 |
57 | public CirclePageIndicator(Context context, AttributeSet attrs) {
58 | this(context, attrs, R.attr.vpiCirclePageIndicatorStyle);
59 | }
60 |
61 | public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {
62 | super(context, attrs, defStyle);
63 | if (isInEditMode()) return;
64 |
65 | //Load defaults from resources
66 | final Resources res = getResources();
67 | final int defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color);
68 | final int defaultFillColor = res.getColor(R.color.default_circle_indicator_fill_color);
69 | final int defaultOrientation = res.getInteger(R.integer.default_circle_indicator_orientation);
70 | final int defaultStrokeColor = res.getColor(R.color.default_circle_indicator_stroke_color);
71 | final float defaultStrokeWidth = res.getDimension(R.dimen.default_circle_indicator_stroke_width);
72 | final float defaultRadius = res.getDimension(R.dimen.default_circle_indicator_radius);
73 | final boolean defaultCentered = res.getBoolean(R.bool.default_circle_indicator_centered);
74 | final boolean defaultSnap = res.getBoolean(R.bool.default_circle_indicator_snap);
75 |
76 | //Retrieve styles attributes
77 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CirclePageIndicator, defStyle, 0);
78 |
79 | mCentered = a.getBoolean(R.styleable.CirclePageIndicator_centered, defaultCentered);
80 | mOrientation = a.getInt(R.styleable.CirclePageIndicator_android_orientation, defaultOrientation);
81 | mPaintPageFill.setStyle(Paint.Style.FILL);
82 | mPaintPageFill.setColor(a.getColor(R.styleable.CirclePageIndicator_pageColor, defaultPageColor));
83 | mPaintStroke.setStyle(Paint.Style.STROKE);
84 | mPaintStroke.setColor(a.getColor(R.styleable.CirclePageIndicator_strokeColor, defaultStrokeColor));
85 | mPaintStroke.setStrokeWidth(a.getDimension(R.styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth));
86 | mPaintFill.setStyle(Paint.Style.FILL);
87 | mPaintFill.setColor(a.getColor(R.styleable.CirclePageIndicator_fillColor, defaultFillColor));
88 | mRadius = a.getDimension(R.styleable.CirclePageIndicator_radius, defaultRadius);
89 | mSnap = a.getBoolean(R.styleable.CirclePageIndicator_snap, defaultSnap);
90 |
91 | Drawable background = a.getDrawable(R.styleable.CirclePageIndicator_android_background);
92 | if (background != null) {
93 | setBackgroundDrawable(background);
94 | }
95 |
96 | a.recycle();
97 |
98 | final ViewConfiguration configuration = ViewConfiguration.get(context);
99 | mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
100 | }
101 |
102 |
103 | public void setCentered(boolean centered) {
104 | mCentered = centered;
105 | invalidate();
106 | }
107 |
108 | public boolean isCentered() {
109 | return mCentered;
110 | }
111 |
112 | public void setPageColor(int pageColor) {
113 | mPaintPageFill.setColor(pageColor);
114 | invalidate();
115 | }
116 |
117 | public int getPageColor() {
118 | return mPaintPageFill.getColor();
119 | }
120 |
121 | public void setFillColor(int fillColor) {
122 | mPaintFill.setColor(fillColor);
123 | invalidate();
124 | }
125 |
126 | public int getFillColor() {
127 | return mPaintFill.getColor();
128 | }
129 |
130 | public void setOrientation(int orientation) {
131 | switch (orientation) {
132 | case HORIZONTAL:
133 | case VERTICAL:
134 | mOrientation = orientation;
135 | requestLayout();
136 | break;
137 |
138 | default:
139 | throw new IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL.");
140 | }
141 | }
142 |
143 | public int getOrientation() {
144 | return mOrientation;
145 | }
146 |
147 | public void setStrokeColor(int strokeColor) {
148 | mPaintStroke.setColor(strokeColor);
149 | invalidate();
150 | }
151 |
152 | public int getStrokeColor() {
153 | return mPaintStroke.getColor();
154 | }
155 |
156 | public void setStrokeWidth(float strokeWidth) {
157 | mPaintStroke.setStrokeWidth(strokeWidth);
158 | invalidate();
159 | }
160 |
161 | public float getStrokeWidth() {
162 | return mPaintStroke.getStrokeWidth();
163 | }
164 |
165 | public void setRadius(float radius) {
166 | mRadius = radius;
167 | invalidate();
168 | }
169 |
170 | public float getRadius() {
171 | return mRadius;
172 | }
173 |
174 | public void setSnap(boolean snap) {
175 | mSnap = snap;
176 | invalidate();
177 | }
178 |
179 | public boolean isSnap() {
180 | return mSnap;
181 | }
182 |
183 | @Override
184 | protected void onDraw(Canvas canvas) {
185 | super.onDraw(canvas);
186 |
187 | if (mViewPager == null) {
188 | return;
189 | }
190 | final int count = mViewPager.getAdapter().getCount();
191 | if (count == 0) {
192 | return;
193 | }
194 |
195 | if (mCurrentPage >= count) {
196 | setCurrentItem(count - 1);
197 | return;
198 | }
199 |
200 | int longSize;
201 | int longPaddingBefore;
202 | int longPaddingAfter;
203 | int shortPaddingBefore;
204 | if (mOrientation == HORIZONTAL) {
205 | longSize = getWidth();
206 | longPaddingBefore = getPaddingLeft();
207 | longPaddingAfter = getPaddingRight();
208 | shortPaddingBefore = getPaddingTop();
209 | } else {
210 | longSize = getHeight();
211 | longPaddingBefore = getPaddingTop();
212 | longPaddingAfter = getPaddingBottom();
213 | shortPaddingBefore = getPaddingLeft();
214 | }
215 |
216 | final float threeRadius = mRadius * 3;
217 | final float shortOffset = shortPaddingBefore + mRadius;
218 | float longOffset = longPaddingBefore + mRadius;
219 | if (mCentered) {
220 | longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((count * threeRadius) / 2.0f);
221 | }
222 |
223 | float dX;
224 | float dY;
225 |
226 | float pageFillRadius = mRadius;
227 | if (mPaintStroke.getStrokeWidth() > 0) {
228 | pageFillRadius -= mPaintStroke.getStrokeWidth() / 2.0f;
229 | }
230 |
231 | //Draw stroked circles
232 | for (int iLoop = 0; iLoop < count; iLoop++) {
233 | float drawLong = longOffset + (iLoop * threeRadius);
234 | if (mOrientation == HORIZONTAL) {
235 | dX = drawLong;
236 | dY = shortOffset;
237 | } else {
238 | dX = shortOffset;
239 | dY = drawLong;
240 | }
241 | // Only paint fill if not completely transparent
242 | if (mPaintPageFill.getAlpha() > 0) {
243 | canvas.drawCircle(dX, dY, pageFillRadius, mPaintPageFill);
244 | }
245 |
246 | // Only paint stroke if a stroke width was non-zero
247 | if (pageFillRadius != mRadius) {
248 | canvas.drawCircle(dX, dY, mRadius, mPaintStroke);
249 | }
250 | }
251 |
252 | //Draw the filled circle according to the current scroll
253 | float cx = (mSnap ? mSnapPage : mCurrentPage) * threeRadius;
254 | if (!mSnap) {
255 | cx += mPageOffset * threeRadius;
256 | }
257 | if (mOrientation == HORIZONTAL) {
258 | dX = longOffset + cx;
259 | dY = shortOffset;
260 | } else {
261 | dX = shortOffset;
262 | dY = longOffset + cx;
263 | }
264 | canvas.drawCircle(dX, dY, mRadius, mPaintFill);
265 | }
266 |
267 | public boolean onTouchEvent(android.view.MotionEvent ev) {
268 | if (super.onTouchEvent(ev)) {
269 | return true;
270 | }
271 | if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
272 | return false;
273 | }
274 |
275 | final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
276 | switch (action) {
277 | case MotionEvent.ACTION_DOWN:
278 | mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
279 | mLastMotionX = ev.getX();
280 | break;
281 |
282 | case MotionEvent.ACTION_MOVE: {
283 | final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
284 | final float x = MotionEventCompat.getX(ev, activePointerIndex);
285 | final float deltaX = x - mLastMotionX;
286 |
287 | if (!mIsDragging) {
288 | if (Math.abs(deltaX) > mTouchSlop) {
289 | mIsDragging = true;
290 | }
291 | }
292 |
293 | if (mIsDragging) {
294 | mLastMotionX = x;
295 | if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) {
296 | mViewPager.fakeDragBy(deltaX);
297 | }
298 | }
299 |
300 | break;
301 | }
302 |
303 | case MotionEvent.ACTION_CANCEL:
304 | case MotionEvent.ACTION_UP:
305 | if (!mIsDragging) {
306 | final int count = mViewPager.getAdapter().getCount();
307 | final int width = getWidth();
308 | final float halfWidth = width / 2f;
309 | final float sixthWidth = width / 6f;
310 |
311 | if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) {
312 | if (action != MotionEvent.ACTION_CANCEL) {
313 | mViewPager.setCurrentItem(mCurrentPage - 1);
314 | }
315 | return true;
316 | } else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) {
317 | if (action != MotionEvent.ACTION_CANCEL) {
318 | mViewPager.setCurrentItem(mCurrentPage + 1);
319 | }
320 | return true;
321 | }
322 | }
323 |
324 | mIsDragging = false;
325 | mActivePointerId = INVALID_POINTER;
326 | if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
327 | break;
328 |
329 | case MotionEventCompat.ACTION_POINTER_DOWN: {
330 | final int index = MotionEventCompat.getActionIndex(ev);
331 | mLastMotionX = MotionEventCompat.getX(ev, index);
332 | mActivePointerId = MotionEventCompat.getPointerId(ev, index);
333 | break;
334 | }
335 |
336 | case MotionEventCompat.ACTION_POINTER_UP:
337 | final int pointerIndex = MotionEventCompat.getActionIndex(ev);
338 | final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
339 | if (pointerId == mActivePointerId) {
340 | final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
341 | mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
342 | }
343 | mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
344 | break;
345 | }
346 |
347 | return true;
348 | }
349 |
350 | @Override
351 | public void setViewPager(ViewPager view) {
352 | if (mViewPager == view) {
353 | return;
354 | }
355 | if (mViewPager != null) {
356 | mViewPager.setOnPageChangeListener(null);
357 | }
358 | if (view.getAdapter() == null) {
359 | throw new IllegalStateException("ViewPager does not have adapter instance.");
360 | }
361 | mViewPager = view;
362 | mViewPager.setOnPageChangeListener(this);
363 | invalidate();
364 | }
365 |
366 | @Override
367 | public void setViewPager(ViewPager view, int initialPosition) {
368 | setViewPager(view);
369 | setCurrentItem(initialPosition);
370 | }
371 |
372 | @Override
373 | public void setCurrentItem(int item) {
374 | if (mViewPager == null) {
375 | throw new IllegalStateException("ViewPager has not been bound.");
376 | }
377 | mViewPager.setCurrentItem(item);
378 | mCurrentPage = item;
379 | invalidate();
380 | }
381 |
382 | @Override
383 | public void notifyDataSetChanged() {
384 | invalidate();
385 | }
386 |
387 | @Override
388 | public void onPageScrollStateChanged(int state) {
389 | mScrollState = state;
390 |
391 | if (mListener != null) {
392 | mListener.onPageScrollStateChanged(state);
393 | }
394 | }
395 |
396 | @Override
397 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
398 | mCurrentPage = position;
399 | mPageOffset = positionOffset;
400 | invalidate();
401 |
402 | if (mListener != null) {
403 | mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
404 | }
405 | }
406 |
407 | @Override
408 | public void onPageSelected(int position) {
409 | if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) {
410 | mCurrentPage = position;
411 | mSnapPage = position;
412 | invalidate();
413 | }
414 |
415 | if (mListener != null) {
416 | mListener.onPageSelected(position);
417 | }
418 | }
419 |
420 | @Override
421 | public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
422 | mListener = listener;
423 | }
424 |
425 | /*
426 | * (non-Javadoc)
427 | *
428 | * @see android.view.View#onMeasure(int, int)
429 | */
430 | @Override
431 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
432 | if (mOrientation == HORIZONTAL) {
433 | setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec));
434 | } else {
435 | setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec));
436 | }
437 | }
438 |
439 | /**
440 | * Determines the width of this view
441 | *
442 | * @param measureSpec A measureSpec packed into an int
443 | * @return The width of the view, honoring constraints from measureSpec
444 | */
445 | private int measureLong(int measureSpec) {
446 | int result;
447 | int specMode = MeasureSpec.getMode(measureSpec);
448 | int specSize = MeasureSpec.getSize(measureSpec);
449 |
450 | if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) {
451 | //We were told how big to be
452 | result = specSize;
453 | } else {
454 | //Calculate the width according the views count
455 | final int count = mViewPager.getAdapter().getCount();
456 | result = (int) (getPaddingLeft() + getPaddingRight()
457 | + (count * 2 * mRadius) + (count - 1) * mRadius + 1);
458 | //Respect AT_MOST value if that was what is called for by measureSpec
459 | if (specMode == MeasureSpec.AT_MOST) {
460 | result = Math.min(result, specSize);
461 | }
462 | }
463 | return result;
464 | }
465 |
466 | /**
467 | * Determines the height of this view
468 | *
469 | * @param measureSpec A measureSpec packed into an int
470 | * @return The height of the view, honoring constraints from measureSpec
471 | */
472 | private int measureShort(int measureSpec) {
473 | int result;
474 | int specMode = MeasureSpec.getMode(measureSpec);
475 | int specSize = MeasureSpec.getSize(measureSpec);
476 |
477 | if (specMode == MeasureSpec.EXACTLY) {
478 | //We were told how big to be
479 | result = specSize;
480 | } else {
481 | //Measure the height
482 | result = (int) (2 * mRadius + getPaddingTop() + getPaddingBottom() + 1);
483 | //Respect AT_MOST value if that was what is called for by measureSpec
484 | if (specMode == MeasureSpec.AT_MOST) {
485 | result = Math.min(result, specSize);
486 | }
487 | }
488 | return result;
489 | }
490 |
491 | @Override
492 | public void onRestoreInstanceState(Parcelable state) {
493 | SavedState savedState = (SavedState) state;
494 | super.onRestoreInstanceState(savedState.getSuperState());
495 | mCurrentPage = savedState.currentPage;
496 | mSnapPage = savedState.currentPage;
497 | requestLayout();
498 | }
499 |
500 | @Override
501 | public Parcelable onSaveInstanceState() {
502 | Parcelable superState = super.onSaveInstanceState();
503 | SavedState savedState = new SavedState(superState);
504 | savedState.currentPage = mCurrentPage;
505 | return savedState;
506 | }
507 |
508 | static class SavedState extends BaseSavedState {
509 | int currentPage;
510 |
511 | public SavedState(Parcelable superState) {
512 | super(superState);
513 | }
514 |
515 | private SavedState(Parcel in) {
516 | super(in);
517 | currentPage = in.readInt();
518 | }
519 |
520 | @Override
521 | public void writeToParcel(Parcel dest, int flags) {
522 | super.writeToParcel(dest, flags);
523 | dest.writeInt(currentPage);
524 | }
525 |
526 | @SuppressWarnings("UnusedDeclaration")
527 | public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
528 | @Override
529 | public SavedState createFromParcel(Parcel in) {
530 | return new SavedState(in);
531 | }
532 |
533 | @Override
534 | public SavedState[] newArray(int size) {
535 | return new SavedState[size];
536 | }
537 | };
538 | }
539 | }
540 |
541 |
--------------------------------------------------------------------------------