diff --git a/ColorPicker/README.md b/ColorPicker/README.md new file mode 100644 index 00000000..452668da --- /dev/null +++ b/ColorPicker/README.md @@ -0,0 +1,3 @@ +# 颜色选择器 + +颜色选择面板,改自[AndroidColorPicker](https://github.com/jbruchanov/AndroidColorPicker) diff --git a/ColorPicker/build.gradle b/ColorPicker/build.gradle new file mode 100644 index 00000000..16cb40a5 --- /dev/null +++ b/ColorPicker/build.gradle @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +apply from: "${rootDir}/gradle/library.gradle" +apply from: "${rootDir}/gradle/publish.gradle" + +dependencies { + implementation androidxLibrary.annotation + implementation project(':BasePicker') +} diff --git a/ColorPicker/consumer-rules.pro b/ColorPicker/consumer-rules.pro new file mode 100644 index 00000000..057cd949 --- /dev/null +++ b/ColorPicker/consumer-rules.pro @@ -0,0 +1 @@ +# 本库模块专用的混淆规则 diff --git a/ColorPicker/src/main/AndroidManifest.xml b/ColorPicker/src/main/AndroidManifest.xml new file mode 100644 index 00000000..fbee3cf0 --- /dev/null +++ b/ColorPicker/src/main/AndroidManifest.xml @@ -0,0 +1,14 @@ + + + diff --git a/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/BrightnessGradientView.java b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/BrightnessGradientView.java new file mode 100644 index 00000000..06cc8f1e --- /dev/null +++ b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/BrightnessGradientView.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.colorpicker; + +import android.content.Context; +import android.util.AttributeSet; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 12:59 + */ +public class BrightnessGradientView extends ColorGradientView { + + public BrightnessGradientView(Context context) { + super(context); + asBrightnessGradient(); + } + + public BrightnessGradientView(Context context, AttributeSet attrs) { + super(context, attrs); + asBrightnessGradient(); + } + + public BrightnessGradientView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + asBrightnessGradient(); + } + +} diff --git a/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/ColorGradientView.java b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/ColorGradientView.java new file mode 100644 index 00000000..e0b59875 --- /dev/null +++ b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/ColorGradientView.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.colorpicker; + +import android.content.Context; +import android.util.AttributeSet; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2015/7/20 + */ +@SuppressWarnings("unused") +public class ColorGradientView extends GradientView { + + public ColorGradientView(Context context) { + super(context); + } + + public ColorGradientView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public ColorGradientView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } + +} \ No newline at end of file diff --git a/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/ColorPicker.java b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/ColorPicker.java new file mode 100644 index 00000000..7511a80a --- /dev/null +++ b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/ColorPicker.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.colorpicker; + +import android.app.Activity; +import android.graphics.Color; +import android.view.View; +import android.widget.TextView; + +import androidx.annotation.CallSuper; +import androidx.annotation.ColorInt; +import androidx.annotation.NonNull; +import androidx.annotation.StyleRes; + +import com.github.gzuliyujiang.basepicker.BottomPicker; +import com.github.gzuliyujiang.basepicker.PickerLog; + +import java.util.Locale; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 10:54 + */ +@SuppressWarnings("unused") +public class ColorPicker extends BottomPicker implements View.OnClickListener, OnColorChangedListener { + protected TextView cancelView; + protected TextView hexView; + protected TextView okView; + protected ColorGradientView colorGradientView; + protected BrightnessGradientView brightnessGradientView; + private boolean initialized = false; + private int initColor = Color.YELLOW; + private OnColorPickedListener onColorPickedListener; + + public ColorPicker(@NonNull Activity activity) { + super(activity); + } + + public ColorPicker(@NonNull Activity activity, @StyleRes int themeResId) { + super(activity, themeResId); + } + + @NonNull + @Override + protected View createContentView(@NonNull Activity activity) { + return View.inflate(activity, R.layout.color_picker_content, null); + } + + @CallSuper + @Override + protected void initView(@NonNull View contentView) { + cancelView = contentView.findViewById(R.id.color_picker_cancel); + hexView = contentView.findViewById(R.id.color_picker_hex); + okView = contentView.findViewById(R.id.color_picker_ok); + colorGradientView = contentView.findViewById(R.id.color_picker_panel); + brightnessGradientView = contentView.findViewById(R.id.color_picker_bright); + } + + @CallSuper + @Override + protected void initData() { + initialized = true; + if (cancelView != null) { + cancelView.setOnClickListener(this); + } + if (okView != null) { + okView.setOnClickListener(this); + } + hexView.getPaint().setStrokeWidth(hexView.getResources().getDisplayMetrics().density * 3); + colorGradientView.setOnColorChangedListener(this); + brightnessGradientView.setOnColorChangedListener(this); + colorGradientView.setBrightnessGradientView(brightnessGradientView); + //将触发onColorChanged,故必须先待其他控件初始化完成后才能调用 + colorGradientView.setColor(initColor); + } + + @CallSuper + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.color_picker_cancel) { + PickerLog.print("cancel clicked"); + onCancel(); + dismiss(); + } else if (id == R.id.color_picker_ok) { + PickerLog.print("ok clicked"); + onOk(); + dismiss(); + } + } + + @Override + public void onColorChanged(@ColorInt int color) { + updateCurrentColor(color); + } + + protected void onCancel() { + + } + + protected void onOk() { + if (onColorPickedListener != null) { + onColorPickedListener.onColorPicked(getCurrentColor()); + } + } + + private void updateCurrentColor(@ColorInt int color) { + String hexString = Utils.toHexString(color, false).toUpperCase(Locale.PRC); + hexView.setText(hexString); + hexView.setTextColor(Utils.reverseColor(color)); + hexView.setBackgroundColor(color); + } + + /** + * 设置初始默认颜色 + * + * @param initColor 颜色值,如:0xFFFF00FF + */ + public void setInitColor(@ColorInt int initColor) { + this.initColor = initColor; + if (initialized) { + colorGradientView.setColor(initColor); + } + } + + public void setOnColorPickListener(OnColorPickedListener onColorPickedListener) { + this.onColorPickedListener = onColorPickedListener; + } + + @ColorInt + public final int getCurrentColor() { + try { + return Color.parseColor("#" + hexView.getText()); + } catch (Exception e) { + PickerLog.print(e); + return initColor; + } + } + + public final TextView getOkView() { + return okView; + } + + public final TextView getHexView() { + return hexView; + } + + public final TextView getCancelView() { + return cancelView; + } + + public final ColorGradientView getColorGradientView() { + return colorGradientView; + } + + public final BrightnessGradientView getBrightnessGradientView() { + return brightnessGradientView; + } + +} diff --git a/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/GradientView.java b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/GradientView.java new file mode 100644 index 00000000..21ad04d5 --- /dev/null +++ b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/GradientView.java @@ -0,0 +1,427 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.colorpicker; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.ComposeShader; +import android.graphics.LinearGradient; +import android.graphics.Paint; +import android.graphics.PorterDuff; +import android.graphics.RectF; +import android.graphics.Shader; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.os.Parcelable; +import android.util.AttributeSet; +import android.view.MotionEvent; +import android.view.View; + +import androidx.annotation.DrawableRes; + +/** + * 颜色选择面板。Adapted from https://github.com/jbruchanov/AndroidColorPicker + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2015/7/20 + */ +@SuppressWarnings("unused") +class GradientView extends View { + private static final int[] GRAD_COLORS = new int[]{Color.RED, Color.YELLOW, Color.GREEN, + Color.CYAN, Color.BLUE, Color.MAGENTA, Color.RED}; + private static final int[] GRAD_ALPHA = new int[]{Color.WHITE, Color.TRANSPARENT}; + + private GradientView gradientView; + private Shader mShader; + private Drawable mPointerDrawable; + private Paint mPaint; + private Paint mPaintBackground; + private final RectF mGradientRect = new RectF(); + + private final float[] mHSV = new float[]{1f, 1f, 1f}; + + private final int[] mSelectedColorGradient = new int[]{0, Color.BLACK}; + private float mRadius = 0; + private int mSelectedColor = 0; + private boolean brightnessGradient = false; + private int mLastX = Integer.MIN_VALUE; + private int mLastY; + private int mPointerHeight; + private int mPointerWidth; + private boolean mLockPointerInBounds = false; + private OnColorChangedListener mOnColorChangedListener; + + public GradientView(Context context) { + super(context); + init(); + } + + public GradientView(Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + public GradientView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(); + } + + private void init() { + setClickable(true); + mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + mPaintBackground = new Paint(Paint.ANTI_ALIAS_FLAG); + mPaintBackground.setColor(Color.WHITE); + setLayerType(View.LAYER_TYPE_SOFTWARE, isInEditMode() ? null : mPaint); + setPointerDrawable(R.mipmap.color_picker_pointer); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + int desiredWidth = 0; + int desiredHeight = 0; + + if (mPointerDrawable != null) { + desiredHeight = mPointerDrawable.getIntrinsicHeight(); + //this is nonsense, but at least have something than 0 + desiredWidth = mPointerDrawable.getIntrinsicWidth(); + } + + int widthMode = MeasureSpec.getMode(widthMeasureSpec); + int widthSize = MeasureSpec.getSize(widthMeasureSpec); + int heightMode = MeasureSpec.getMode(heightMeasureSpec); + int heightSize = MeasureSpec.getSize(heightMeasureSpec); + + int width; + int height; + + //Measure Width + if (widthMode == MeasureSpec.EXACTLY) { + //Must be this size + width = widthSize; + } else if (widthMode == MeasureSpec.AT_MOST) { + //Can't be bigger than... + width = Math.min(desiredWidth, widthSize); + } else { + //Be whatever you want + width = desiredWidth; + } + + //Measure Height + if (heightMode == MeasureSpec.EXACTLY) { + //Must be this size + height = heightSize; + } else if (heightMode == MeasureSpec.AT_MOST) { + //Can't be bigger than... + height = Math.min(desiredHeight, heightSize); + } else { + //Be whatever you want + height = desiredHeight; + } + + //MUST CALL THIS + setMeasuredDimension(width, height); + } + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + if (mShader != null) { + canvas.drawRoundRect(mGradientRect, mRadius, mRadius, mPaintBackground); + canvas.drawRoundRect(mGradientRect, mRadius, mRadius, mPaint); + } + + onDrawPointer(canvas); + + } + + private void onDrawPointer(Canvas canvas) { + if (mPointerDrawable != null) { + int vh = getHeight(); + int pwh = mPointerWidth >> 1; + int phh = mPointerHeight >> 1; + float tx, ty; + if (!brightnessGradient) { + // fixed: 17-1-7 Math operands should be cast before assignment + tx = (float) (mLastX - pwh); + ty = (float) (mLastY - phh); + if (mLockPointerInBounds) { + tx = Math.max(mGradientRect.left, Math.min(tx, mGradientRect.right - mPointerWidth)); + ty = Math.max(mGradientRect.top, Math.min(ty, mGradientRect.bottom - mPointerHeight)); + } else { + tx = Math.max(mGradientRect.left - pwh, Math.min(tx, mGradientRect.right - pwh)); + ty = Math.max(mGradientRect.top - pwh, Math.min(ty, mGradientRect.bottom - phh)); + } + } else {//vertical lock + tx = (float) (mLastX - pwh); + ty = mPointerHeight != mPointerDrawable.getIntrinsicHeight() ? (vh >> 1) - phh : 0; + if (mLockPointerInBounds) { + tx = Math.max(mGradientRect.left, Math.min(tx, mGradientRect.right - mPointerWidth)); + ty = Math.max(mGradientRect.top, Math.min(ty, mGradientRect.bottom - mPointerHeight)); + } else { + tx = Math.max(mGradientRect.left - pwh, Math.min(tx, mGradientRect.right - pwh)); + ty = Math.max(mGradientRect.top - pwh, Math.min(ty, mGradientRect.bottom - phh)); + } + } + canvas.translate(tx, ty); + mPointerDrawable.draw(canvas); + canvas.translate(-tx, -ty); + } + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + mGradientRect.set(getPaddingLeft(), getPaddingTop(), right - left - getPaddingRight(), bottom - top - getPaddingBottom()); + if (changed) { + buildShader(); + } + + if (mPointerDrawable != null) { + int h = (int) mGradientRect.height(); + int ph = mPointerDrawable.getIntrinsicHeight(); + int pw = mPointerDrawable.getIntrinsicWidth(); + mPointerHeight = ph; + mPointerWidth = pw; + if (h < ph) { + mPointerHeight = h; + mPointerWidth = (int) (pw * (h / (float) ph)); + } + mPointerDrawable.setBounds(0, 0, mPointerWidth, mPointerHeight); + updatePointerPosition(); + } + } + + private void buildShader() { + if (brightnessGradient) { + mShader = new LinearGradient(mGradientRect.left, mGradientRect.top, mGradientRect.right, mGradientRect.top, mSelectedColorGradient, null, Shader.TileMode.CLAMP); + } else { + LinearGradient gradientShader = new LinearGradient(mGradientRect.left, mGradientRect.top, mGradientRect.right, mGradientRect.top, GRAD_COLORS, null, Shader.TileMode.CLAMP); + LinearGradient alphaShader = new LinearGradient(0, mGradientRect.top + (mGradientRect.height() / 3), 0, mGradientRect.bottom, GRAD_ALPHA, null, Shader.TileMode.CLAMP); + mShader = new ComposeShader(alphaShader, gradientShader, PorterDuff.Mode.MULTIPLY); + } + mPaint.setShader(mShader); + } + + public void setRadius(float radius) { + // fixed: 17-1-7 Equality tests should not be made with floating point values. + if ((int) radius != (int) mRadius) { + mRadius = radius; + invalidate(); + } + } + + @SuppressLint("ClickableViewAccessibility") + @Override + public boolean onTouchEvent(MotionEvent event) { + mLastX = (int) event.getX(); + mLastY = (int) event.getY(); + onUpdateColorSelection(mLastX, mLastY); + invalidate(); + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + getParent().requestDisallowInterceptTouchEvent(true); + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + getParent().requestDisallowInterceptTouchEvent(false); + break; + } + return super.onTouchEvent(event); + } + + protected void onUpdateColorSelection(int x, int y) { + x = (int) Math.max(mGradientRect.left, Math.min(x, mGradientRect.right)); + y = (int) Math.max(mGradientRect.top, Math.min(y, mGradientRect.bottom)); + if (brightnessGradient) { + float b = pointToValueBrightness(x); + mHSV[2] = b; + mSelectedColor = Color.HSVToColor(mHSV); + } else { + float hue = pointToHue(x); + float sat = pointToSaturation(y); + mHSV[0] = hue; + mHSV[1] = sat; + mHSV[2] = 1f; + mSelectedColor = Color.HSVToColor(mHSV); + } + dispatchColorChanged(mSelectedColor); + } + + protected void dispatchColorChanged(int color) { + if (gradientView != null) { + gradientView.setColor(color, false); + } + if (mOnColorChangedListener != null) { + mOnColorChangedListener.onColorChanged(color); + } + } + + public final void asBrightnessGradient() { + this.brightnessGradient = true; + } + + public void setBrightnessGradientView(GradientView gradientView) { + if (this.gradientView != gradientView) { + this.gradientView = gradientView; + if (this.gradientView != null) { + this.gradientView.asBrightnessGradient(); + this.gradientView.setColor(mSelectedColor); + } + } + } + + public int getSelectedColor() { + return mSelectedColor; + } + + public void setColor(int selectedColor) { + setColor(selectedColor, true); + } + + protected void setColor(int selectedColor, boolean updatePointers) { + Color.colorToHSV(selectedColor, mHSV); + if (brightnessGradient) { + mSelectedColorGradient[0] = getColorForGradient(mHSV); + mSelectedColor = Color.HSVToColor(mHSV); + buildShader(); + if (mLastX != Integer.MIN_VALUE) { + mHSV[2] = pointToValueBrightness(mLastX); + } + selectedColor = Color.HSVToColor(mHSV); + } + if (updatePointers) { + updatePointerPosition(); + } + mSelectedColor = selectedColor; + invalidate(); + dispatchColorChanged(mSelectedColor); + } + + private int getColorForGradient(float[] hsv) { + // fixed: 17-1-7 Equality tests should not be made with floating point values. + if ((int) hsv[2] != 1) { + float oldV = hsv[2]; + hsv[2] = 1; + int color = Color.HSVToColor(hsv); + hsv[2] = oldV; + return color; + } else { + return Color.HSVToColor(hsv); + } + } + + private void updatePointerPosition() { + if (mGradientRect.width() != 0 && mGradientRect.height() != 0) { + if (!brightnessGradient) { + mLastX = hueToPoint(mHSV[0]); + mLastY = saturationToPoint(mHSV[1]); + } else { + mLastX = brightnessToPoint(mHSV[2]); + } + } + } + + public void setOnColorChangedListener(OnColorChangedListener onColorChangedListener) { + mOnColorChangedListener = onColorChangedListener; + } + + //region HSL math + + private float pointToHue(float x) { + x = x - mGradientRect.left; + return x * 360f / mGradientRect.width(); + } + + private int hueToPoint(float hue) { + return (int) (mGradientRect.left + ((hue * mGradientRect.width()) / 360)); + } + + private float pointToSaturation(float y) { + y = y - mGradientRect.top; + return 1 - (1.f / mGradientRect.height() * y); + } + + private int saturationToPoint(float sat) { + sat = 1 - sat; + return (int) (mGradientRect.top + (mGradientRect.height() * sat)); + } + + private float pointToValueBrightness(float x) { + x = x - mGradientRect.left; + return 1 - (1.f / mGradientRect.width() * x); + } + + private int brightnessToPoint(float val) { + val = 1 - val; + return (int) (mGradientRect.left + (mGradientRect.width() * val)); + } + //endregion HSL math + + public void setPointerDrawable(Drawable pointerDrawable) { + if (pointerDrawable == null) { + return; + } + if (mPointerDrawable != pointerDrawable) { + mPointerDrawable = pointerDrawable; + requestLayout(); + } + } + + public void setPointerDrawable(@DrawableRes int pointerDrawable) { + setPointerDrawable(getResources().getDrawable(pointerDrawable)); + } + + public void recycle() { + mPaint = null; + mPaintBackground = null; + if (mPointerDrawable instanceof BitmapDrawable) { + Bitmap bitmap = ((BitmapDrawable) mPointerDrawable).getBitmap(); + if (null != bitmap && !bitmap.isRecycled()) { + bitmap.recycle(); + } + } + } + + public void setLockPointerInBounds(boolean lockPointerInBounds) { + if (lockPointerInBounds != mLockPointerInBounds) { + mLockPointerInBounds = lockPointerInBounds; + invalidate(); + } + } + + @Override + protected Parcelable onSaveInstanceState() { + Parcelable superState = super.onSaveInstanceState(); + SavedState ss = new SavedState(superState); + ss.isBrightnessGradient = brightnessGradient; + ss.color = mSelectedColor; + return ss; + } + + @Override + protected void onRestoreInstanceState(Parcelable state) { + if (!(state instanceof SavedState)) { + super.onRestoreInstanceState(state); + return; + } + SavedState ss = (SavedState) state; + super.onRestoreInstanceState(ss.getSuperState()); + brightnessGradient = ss.isBrightnessGradient; + setColor(ss.color, true); + } + +} \ No newline at end of file diff --git a/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/OnColorChangedListener.java b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/OnColorChangedListener.java new file mode 100644 index 00000000..05e1e10b --- /dev/null +++ b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/OnColorChangedListener.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.colorpicker; + +import androidx.annotation.ColorInt; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2015/7/20 + */ +public interface OnColorChangedListener { + + void onColorChanged(@ColorInt int color); + +} diff --git a/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/OnColorPickedListener.java b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/OnColorPickedListener.java new file mode 100644 index 00000000..f7e9bb2b --- /dev/null +++ b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/OnColorPickedListener.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.colorpicker; + +import androidx.annotation.ColorInt; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2015/7/20 + */ +public interface OnColorPickedListener { + + void onColorPicked(@ColorInt int pickedColor); + +} diff --git a/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/SavedState.java b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/SavedState.java new file mode 100644 index 00000000..efa81434 --- /dev/null +++ b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/SavedState.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.colorpicker; + +import android.os.Parcel; +import android.os.Parcelable; +import android.view.View; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 10:56 + */ +class SavedState extends View.BaseSavedState { + int color; + boolean isBrightnessGradient; + + SavedState(Parcelable superState) { + super(superState); + } + + private SavedState(Parcel in) { + super(in); + color = in.readInt(); + isBrightnessGradient = in.readInt() == 1; + } + + @Override + public void writeToParcel(Parcel out, int flags) { + super.writeToParcel(out, flags); + out.writeInt(color); + out.writeInt(isBrightnessGradient ? 1 : 0); + } + + public static final Creator CREATOR = + new Creator() { + public SavedState createFromParcel(Parcel in) { + return new SavedState(in); + } + + public SavedState[] newArray(int size) { + return new SavedState[size]; + } + }; + +} diff --git a/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/Utils.java b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/Utils.java new file mode 100644 index 00000000..6ebde6a4 --- /dev/null +++ b/ColorPicker/src/main/java/com/github/gzuliyujiang/colorpicker/Utils.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.colorpicker; + +import android.graphics.Color; + +import androidx.annotation.ColorInt; +import androidx.annotation.NonNull; + +import com.github.gzuliyujiang.basepicker.PickerLog; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 11:30 + */ +class Utils { + + @ColorInt + public static int reverseColor(@ColorInt int color) { + int alpha = Color.alpha(color); + int red = Color.red(color); + int green = Color.green(color); + int blue = Color.blue(color); + return Color.argb(alpha, 255 - red, 255 - green, 255 - blue); + } + + /** + * 转换为6位十六进制颜色代码,不含“#” + */ + @NonNull + public static String toHexString(@ColorInt int color, boolean includeAlpha) { + String alpha = Integer.toHexString(Color.alpha(color)); + String red = Integer.toHexString(Color.red(color)); + String green = Integer.toHexString(Color.green(color)); + String blue = Integer.toHexString(Color.blue(color)); + if (alpha.length() == 1) { + alpha = "0" + alpha; + } + if (red.length() == 1) { + red = "0" + red; + } + if (green.length() == 1) { + green = "0" + green; + } + if (blue.length() == 1) { + blue = "0" + blue; + } + String colorString; + if (includeAlpha) { + colorString = alpha + red + green + blue; + PickerLog.print(String.format("%s to color string is %s", color, colorString)); + } else { + colorString = red + green + blue; + PickerLog.print(String.format("%s to color string is %s%s%s%s, exclude alpha is %s", color, alpha, red, green, blue, colorString)); + } + return colorString; + } + +} diff --git a/ColorPicker/src/main/res/layout/color_picker_content.xml b/ColorPicker/src/main/res/layout/color_picker_content.xml new file mode 100644 index 00000000..f1de1618 --- /dev/null +++ b/ColorPicker/src/main/res/layout/color_picker_content.xml @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ColorPicker/src/main/res/mipmap-xxhdpi/color_picker_pointer.png b/ColorPicker/src/main/res/mipmap-xxhdpi/color_picker_pointer.png new file mode 100644 index 00000000..3a7da96a Binary files /dev/null and b/ColorPicker/src/main/res/mipmap-xxhdpi/color_picker_pointer.png differ diff --git a/FilePicker/README.md b/FilePicker/README.md new file mode 100644 index 00000000..572ff04b --- /dev/null +++ b/FilePicker/README.md @@ -0,0 +1,2 @@ +# 文件/目录选择器 + diff --git a/FilePicker/build.gradle b/FilePicker/build.gradle new file mode 100644 index 00000000..2b8b68b9 --- /dev/null +++ b/FilePicker/build.gradle @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +apply from: "${rootDir}/gradle/library.gradle" +apply from: "${rootDir}/gradle/publish.gradle" + +dependencies { + implementation androidxLibrary.annotation + implementation androidxLibrary.recyclerview + implementation project(':BasePicker') +} diff --git a/FilePicker/consumer-rules.pro b/FilePicker/consumer-rules.pro new file mode 100644 index 00000000..057cd949 --- /dev/null +++ b/FilePicker/consumer-rules.pro @@ -0,0 +1 @@ +# 本库模块专用的混淆规则 diff --git a/FilePicker/src/main/AndroidManifest.xml b/FilePicker/src/main/AndroidManifest.xml new file mode 100644 index 00000000..e159d568 --- /dev/null +++ b/FilePicker/src/main/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + \ No newline at end of file diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/FileExplorer.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/FileExplorer.java new file mode 100644 index 00000000..75c1bd36 --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/FileExplorer.java @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker; + +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.os.Environment; +import android.text.TextUtils; +import android.util.AttributeSet; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +import com.github.gzuliyujiang.basepicker.PickerLog; +import com.github.gzuliyujiang.filepicker.adapter.FileAdapter; +import com.github.gzuliyujiang.filepicker.adapter.FileEntity; +import com.github.gzuliyujiang.filepicker.adapter.PathAdapter; +import com.github.gzuliyujiang.filepicker.annotation.ExplorerMode; +import com.github.gzuliyujiang.filepicker.contract.OnFileClickedListener; +import com.github.gzuliyujiang.filepicker.contract.OnPathClickedListener; + +import java.io.File; +import java.util.Locale; + +/** + * 文件浏览器 + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 18:50 + */ +@SuppressWarnings("unused") +public class FileExplorer extends FrameLayout { + private int explorerMode = ExplorerMode.FILE; + private File initDir; + private CharSequence emptyHint; + private FileAdapter fileAdapter; + private PathAdapter pathAdapter; + private RecyclerView fileListView; + private TextView emptyHintView; + private View bottomLineView; + private RecyclerView pathListView; + private OnFileClickedListener onFileClickedListener; + + public FileExplorer(Context context) { + super(context); + init(context); + } + + public FileExplorer(Context context, AttributeSet attrs) { + super(context, attrs); + init(context); + } + + public FileExplorer(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(context); + } + + public FileExplorer(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + init(context); + } + + private void init(Context context) { + View contentView = inflate(context, R.layout.file_picker_content, this); + fileListView = contentView.findViewById(R.id.file_picker_file_list); + fileAdapter = new FileAdapter(context); + fileListView.setAdapter(fileAdapter); + emptyHint = Locale.getDefault().getDisplayLanguage().contains("中文") ? "<空>" : ""; + emptyHintView = contentView.findViewById(R.id.file_picker_empty_hint); + emptyHintView.setText(emptyHint); + bottomLineView = contentView.findViewById(R.id.file_picker_bottom_line); + pathAdapter = new PathAdapter(context); + pathListView = contentView.findViewById(R.id.file_picker_path_list); + pathListView.setAdapter(pathAdapter); + fileAdapter.setOnlyListDir(false); + fileAdapter.setShowHideDir(true); + fileAdapter.setShowHomeDir(true); + fileAdapter.setShowUpDir(true); + initDir = getDefaultDir(); + fileAdapter.loadData(initDir); + fileAdapter.setOnPathClickedListener(new OnPathClickedListener() { + @Override + public void onPathClicked(int position, @NonNull String path) { + FileEntity entity = fileAdapter.getItem(position); + PickerLog.print("clicked file item: " + entity); + File file = entity.getFile(); + if (file.isDirectory()) { + refreshCurrent(file); + return; + } + if (onFileClickedListener != null) { + onFileClickedListener.onFileClicked(file); + } + } + }); + pathAdapter.setOnPathClickedListener(new OnPathClickedListener() { + @Override + public void onPathClicked(int position, @NonNull String path) { + PickerLog.print("clicked path name: " + path); + refreshCurrent(new File(path)); + } + }); + } + + public final File getDefaultDir() { + if (initDir != null) { + return initDir; + } + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + return getContext().getExternalFilesDir(null); + } else { + return getContext().getFilesDir(); + } + } + + public void setInitDir(@ExplorerMode int explorerMode, File initDir) { + if (this.explorerMode != explorerMode) { + this.explorerMode = explorerMode; + fileAdapter.setOnlyListDir(explorerMode == ExplorerMode.DIRECTORY); + } + if (initDir == null) { + initDir = getDefaultDir(); + } + this.initDir = initDir; + refreshCurrent(initDir); + } + + @ExplorerMode + public final int getExplorerMode() { + return explorerMode; + } + + public void setEmptyHint(@NonNull CharSequence emptyHint) { + if (TextUtils.equals(this.emptyHint, emptyHint)) { + return; + } + this.emptyHint = emptyHint; + emptyHintView.setText(emptyHint); + } + + public final void refreshCurrent(File current) { + if (current == null) { + return; + } + pathAdapter.updatePath(current); + fileAdapter.loadData(current); + int itemCount = fileAdapter.getItemCount(); + if (fileAdapter.isShowHomeDir()) { + itemCount--; + } + if (fileAdapter.isShowUpDir()) { + itemCount--; + } + if (itemCount < 1) { + PickerLog.print("no files, or dir is empty"); + emptyHintView.setVisibility(View.VISIBLE); + emptyHintView.setText(emptyHint); + } else { + PickerLog.print("files or dirs count: " + itemCount); + emptyHintView.setVisibility(View.GONE); + } + } + + public void setOnFileClickedListener(OnFileClickedListener listener) { + this.onFileClickedListener = listener; + } + + public void setAllowExtensions(String[] allowExtensions) { + fileAdapter.setAllowExtensions(allowExtensions); + } + + public void setShowUpDir(boolean showUpDir) { + fileAdapter.setShowUpDir(showUpDir); + } + + public void setShowHomeDir(boolean showHomeDir) { + fileAdapter.setShowHomeDir(showHomeDir); + } + + public void setShowHideDir(boolean showHideDir) { + fileAdapter.setShowHideDir(showHideDir); + } + + public void setFileIcon(Drawable fileIcon) { + fileAdapter.setFileIcon(fileIcon); + } + + public void setFolderIcon(Drawable folderIcon) { + fileAdapter.setFolderIcon(folderIcon); + } + + public void setHomeIcon(Drawable homeIcon) { + fileAdapter.setHomeIcon(homeIcon); + } + + public void setUpIcon(Drawable upIcon) { + fileAdapter.setUpIcon(upIcon); + } + + public void setArrowIcon(Drawable arrowIcon) { + pathAdapter.setArrowIcon(arrowIcon); + } + + public void setItemHeight(int itemHeight) { + fileAdapter.setItemHeight(itemHeight); + } + + public final FileAdapter getFileAdapter() { + return fileAdapter; + } + + public final PathAdapter getPathAdapter() { + return pathAdapter; + } + + public final File getCurrentFile() { + return fileAdapter.getCurrentFile(); + } + + public final RecyclerView getFileListView() { + return fileListView; + } + + public final TextView getEmptyHintView() { + return emptyHintView; + } + + public final View getBottomLineView() { + return bottomLineView; + } + + public final RecyclerView getPathListView() { + return pathListView; + } + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/FilePicker.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/FilePicker.java new file mode 100644 index 00000000..973593fd --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/FilePicker.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker; + +import android.app.Activity; +import android.view.View; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.StyleRes; +import androidx.recyclerview.widget.RecyclerView; + +import com.github.gzuliyujiang.basepicker.ConfirmPicker; +import com.github.gzuliyujiang.basepicker.PickerLog; +import com.github.gzuliyujiang.filepicker.annotation.ExplorerMode; +import com.github.gzuliyujiang.filepicker.contract.OnFileClickedListener; +import com.github.gzuliyujiang.filepicker.contract.OnFilePickedListener; + +import java.io.File; + +/** + * 文件目录选择器 + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2015/9/29 + */ +@SuppressWarnings("unused") +public class FilePicker extends ConfirmPicker { + private int explorerMode = ExplorerMode.FILE; + private File initDir; + private FileExplorer fileExplorer; + private OnFilePickedListener onFilePickedListener; + private boolean initialized = false; + + public FilePicker(Activity activity) { + super(activity); + } + + public FilePicker(@NonNull Activity activity, @StyleRes int themeResId) { + super(activity, themeResId); + } + + @NonNull + @Override + protected View createBodyView(@NonNull Activity activity) { + fileExplorer = new FileExplorer(activity); + return fileExplorer; + } + + @Override + protected void initData() { + super.initData(); + initialized = true; + if (explorerMode == ExplorerMode.FILE) { + okView.setVisibility(View.INVISIBLE); + } + setBodyHeight(300); + setInitDir(explorerMode, initDir); + } + + @Override + protected void onCancel() { + + } + + @Override + protected void onOk() { + File currentFile = fileExplorer.getCurrentFile(); + PickerLog.print("picked directory: " + currentFile); + if (onFilePickedListener != null) { + onFilePickedListener.onFilePicked(currentFile); + } + } + + public void setInitDir(@ExplorerMode int explorerMode, File initDir) { + this.explorerMode = explorerMode; + this.initDir = initDir; + if (initialized) { + fileExplorer.setInitDir(explorerMode, initDir); + } + } + + public void setOnFilePickedListener(OnFilePickedListener listener) { + this.onFilePickedListener = listener; + fileExplorer.setOnFileClickedListener(new OnFileClickedListener() { + @Override + public void onFileClicked(@NonNull File file) { + if (explorerMode == ExplorerMode.FILE) { + dismiss(); + onFilePickedListener.onFilePicked(file); + } + } + }); + } + + public final File getCurrentFile() { + return fileExplorer.getCurrentFile(); + } + + public final FileExplorer getFileExplorer() { + return fileExplorer; + } + + public final RecyclerView getFileListView() { + return fileExplorer.getFileListView(); + } + + public final TextView getEmptyHintView() { + return fileExplorer.getEmptyHintView(); + } + + public final View getBottomLineView() { + return fileExplorer.getBottomLineView(); + } + + public final RecyclerView getPathListView() { + return fileExplorer.getPathListView(); + } + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/FileAdapter.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/FileAdapter.java new file mode 100644 index 00000000..8625296d --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/FileAdapter.java @@ -0,0 +1,398 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.adapter; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Color; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.Dimension; +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.RecyclerView; + +import com.github.gzuliyujiang.basepicker.PickerLog; +import com.github.gzuliyujiang.filepicker.R; +import com.github.gzuliyujiang.filepicker.annotation.FileSort; +import com.github.gzuliyujiang.filepicker.contract.OnPathClickedListener; +import com.github.gzuliyujiang.filepicker.filter.SimpleFilter; +import com.github.gzuliyujiang.filepicker.sort.SortByExtension; +import com.github.gzuliyujiang.filepicker.sort.SortByName; +import com.github.gzuliyujiang.filepicker.sort.SortBySize; +import com.github.gzuliyujiang.filepicker.sort.SortByTime; + +import java.io.File; +import java.io.FileFilter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * 文件目录数据适配 + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2014/05/23 18:02 + */ +@SuppressWarnings("unused") +public class FileAdapter extends RecyclerView.Adapter { + private final Context context; + public static final String DIR_ROOT = "."; + public static final String DIR_PARENT = ".."; + private final List data = new ArrayList<>(); + private File rootDir = null; + private File currentFile = null; + private String[] allowExtensions = null; + private boolean onlyListDir = false; + private boolean showHomeDir = true; + private boolean showUpDir = true; + private boolean showHideDir = true; + private int fileSort = FileSort.BY_NAME_ASC; + private int itemHeight = 40; + private Drawable homeIcon; + private Drawable upIcon; + private Drawable folderIcon; + private Drawable fileIcon; + private OnPathClickedListener onPathClickedListener; + + public FileAdapter(@NonNull Context context) { + this.context = context; + homeIcon = ContextCompat.getDrawable(context, R.mipmap.file_picker_home); + upIcon = ContextCompat.getDrawable(context, R.mipmap.file_picker_up); + folderIcon = ContextCompat.getDrawable(context, R.mipmap.file_picker_folder); + fileIcon = ContextCompat.getDrawable(context, R.mipmap.file_picker_file); + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + LinearLayout layout = new LinearLayout(context); + layout.setBackground(new StateDrawable(Color.WHITE, Color.LTGRAY)); + layout.setOrientation(LinearLayout.HORIZONTAL); + layout.setGravity(Gravity.CENTER_VERTICAL); + int height = (int) (itemHeight * context.getResources().getDisplayMetrics().density); + int matchParent = ViewGroup.LayoutParams.MATCH_PARENT; + layout.setLayoutParams(new ViewGroup.LayoutParams(matchParent, height)); + int padding = (int) (5 * context.getResources().getDisplayMetrics().density); + layout.setPadding(padding, padding, padding, padding); + ImageView imageView = new ImageView(context); + int wh = (int) (30 * context.getResources().getDisplayMetrics().density); + imageView.setLayoutParams(new LinearLayout.LayoutParams(wh, wh)); + imageView.setImageResource(android.R.drawable.ic_menu_report_image); + layout.addView(imageView); + TextView textView = new TextView(context); + LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(matchParent, matchParent); + tvParams.leftMargin = (int) (10 * context.getResources().getDisplayMetrics().density); + textView.setLayoutParams(tvParams); + textView.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); + textView.setSingleLine(); + layout.addView(textView); + ViewHolder viewHolder = new ViewHolder(layout); + viewHolder.textView = textView; + viewHolder.imageView = imageView; + return viewHolder; + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { + final FileEntity item = getItem(position); + holder.imageView.setImageDrawable(item.getIcon()); + holder.textView.setText(item.getName()); + if (onPathClickedListener == null) { + return; + } + holder.itemView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + onPathClickedListener.onPathClicked(position, item.getFile().getAbsolutePath()); + } + }); + } + + @Override + public long getItemId(int position) { + return position; + } + + @Override + public int getItemCount() { + return data.size(); + } + + public void setItemHeight(@Dimension(unit = Dimension.DP) int itemHeight) { + this.itemHeight = itemHeight; + notifyDataSetChanged(); + } + + public void setFileIcon(Drawable fileIcon) { + if (fileIcon == null) { + return; + } + this.fileIcon = fileIcon; + notifyDataSetChanged(); + } + + public void setFolderIcon(Drawable folderIcon) { + if (folderIcon == null) { + return; + } + this.folderIcon = folderIcon; + notifyDataSetChanged(); + } + + public void setHomeIcon(Drawable homeIcon) { + if (homeIcon == null) { + return; + } + this.homeIcon = homeIcon; + notifyDataSetChanged(); + } + + public void setUpIcon(Drawable upIcon) { + if (upIcon == null) { + return; + } + this.upIcon = upIcon; + notifyDataSetChanged(); + } + + /** + * 允许的扩展名 + */ + public void setAllowExtensions(String[] allowExtensions) { + if (this.allowExtensions != null && Arrays.equals(this.allowExtensions, allowExtensions)) { + return; + } + this.allowExtensions = allowExtensions; + loadData(getCurrentFile()); + } + + /** + * 是否仅仅读取目录 + */ + public void setOnlyListDir(boolean onlyListDir) { + if (this.onlyListDir == onlyListDir) { + return; + } + this.onlyListDir = onlyListDir; + loadData(getCurrentFile()); + } + + public boolean isOnlyListDir() { + return onlyListDir; + } + + /** + * 是否显示返回主目录 + */ + public void setShowHomeDir(boolean showHomeDir) { + if (this.showHomeDir == showHomeDir) { + return; + } + this.showHomeDir = showHomeDir; + loadData(getCurrentFile()); + } + + public boolean isShowHomeDir() { + return showHomeDir; + } + + /** + * 是否显示返回上一级 + */ + public void setShowUpDir(boolean showUpDir) { + if (this.showUpDir == showUpDir) { + return; + } + this.showUpDir = showUpDir; + loadData(getCurrentFile()); + } + + public boolean isShowUpDir() { + return showUpDir; + } + + /** + * 是否显示隐藏的目录(以“.”开头) + */ + public void setShowHideDir(boolean showHideDir) { + if (this.showHideDir == showHideDir) { + return; + } + this.showHideDir = showHideDir; + loadData(getCurrentFile()); + } + + public boolean isShowHideDir() { + return showHideDir; + } + + @FileSort + public int getFileSort() { + return fileSort; + } + + public void setFileSort(@FileSort int fileSort) { + if (this.fileSort == fileSort) { + return; + } + this.fileSort = fileSort; + loadData(getCurrentFile()); + } + + public File getCurrentFile() { + return currentFile; + } + + public void loadData(File dir) { + if (dir == null) { + PickerLog.print("current directory is null"); + return; + } + List entities = new ArrayList<>(); + if (rootDir == null) { + rootDir = dir; + } + PickerLog.print("current directory path: " + dir); + currentFile = dir; + if (showHomeDir) { + //添加“返回主目录” + FileEntity root = new FileEntity(); + root.setIcon(homeIcon); + root.setName(DIR_ROOT); + root.setFile(rootDir); + entities.add(root); + } + if (showUpDir && !File.separator.equals(dir.getAbsolutePath())) { + //添加“返回上一级目录” + FileEntity parent = new FileEntity(); + parent.setIcon(upIcon); + parent.setName(DIR_PARENT); + parent.setFile(dir.getParentFile()); + entities.add(parent); + } + List files = listFiles(currentFile, new SimpleFilter(onlyListDir, allowExtensions)); + sortFiles(files, fileSort); + for (File file : files) { + if (!showHideDir && file.getName().startsWith(".")) { + continue; + } + FileEntity FileEntity = new FileEntity(); + if (file.isDirectory()) { + FileEntity.setIcon(folderIcon); + } else { + FileEntity.setIcon(fileIcon); + } + FileEntity.setName(file.getName()); + FileEntity.setFile(file); + entities.add(FileEntity); + } + data.clear(); + data.addAll(entities); + notifyDataSetChanged(); + } + + public final void recycleData() { + data.clear(); + if (homeIcon instanceof BitmapDrawable) { + Bitmap homeBitmap = ((BitmapDrawable) homeIcon).getBitmap(); + if (null != homeBitmap && !homeBitmap.isRecycled()) { + homeBitmap.recycle(); + } + } + if (upIcon instanceof BitmapDrawable) { + Bitmap upBitmap = ((BitmapDrawable) upIcon).getBitmap(); + if (null != upBitmap && !upBitmap.isRecycled()) { + upBitmap.recycle(); + } + } + if (folderIcon instanceof BitmapDrawable) { + Bitmap folderBitmap = ((BitmapDrawable) folderIcon).getBitmap(); + if (null != folderBitmap && !folderBitmap.isRecycled()) { + folderBitmap.recycle(); + } + } + if (fileIcon instanceof BitmapDrawable) { + Bitmap fileBitmap = ((BitmapDrawable) fileIcon).getBitmap(); + if (null != fileBitmap && !fileBitmap.isRecycled()) { + fileBitmap.recycle(); + } + } + } + + public void setOnPathClickedListener(OnPathClickedListener listener) { + onPathClickedListener = listener; + } + + public FileEntity getItem(int position) { + return data.get(position); + } + + /** + * 列出指定目录下的所有子目录 + */ + private List listFiles(File startDir, FileFilter fileFilter) { + PickerLog.print(String.format("list dir %s", startDir)); + if (!startDir.isDirectory()) { + return new ArrayList<>(); + } + File[] dirs = startDir.listFiles(fileFilter); + if (dirs == null) { + return new ArrayList<>(); + } + return Arrays.asList(dirs); + } + + private void sortFiles(List files, @FileSort int sort) { + switch (sort) { + case FileSort.BY_NAME_ASC: + Collections.sort(files, new SortByName()); + break; + case FileSort.BY_NAME_DESC: + Collections.sort(files, new SortByName()); + Collections.reverse(files); + break; + case FileSort.BY_TIME_ASC: + Collections.sort(files, new SortByTime()); + break; + case FileSort.BY_TIME_DESC: + Collections.sort(files, new SortByTime()); + Collections.reverse(files); + break; + case FileSort.BY_SIZE_ASC: + Collections.sort(files, new SortBySize()); + break; + case FileSort.BY_SIZE_DESC: + Collections.sort(files, new SortBySize()); + Collections.reverse(files); + break; + case FileSort.BY_EXTENSION_ASC: + Collections.sort(files, new SortByExtension()); + break; + case FileSort.BY_EXTENSION_DESC: + Collections.sort(files, new SortByExtension()); + Collections.reverse(files); + break; + } + } + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/FileEntity.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/FileEntity.java new file mode 100644 index 00000000..9c824152 --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/FileEntity.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.adapter; + +import android.graphics.drawable.Drawable; + +import androidx.annotation.NonNull; + +import java.io.File; +import java.io.Serializable; + +/** + * 文件项信息 + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2014/05/23 18:02 + */ +public class FileEntity implements Serializable { + private Drawable icon; + private String name; + private File file; + + public void setIcon(Drawable icon) { + this.icon = icon; + } + + public Drawable getIcon() { + return icon; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + @NonNull + @Override + public String toString() { + return "FileEntity{" + + "name='" + name + '\'' + + ", file='" + file + '\'' + + '}'; + } + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/PathAdapter.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/PathAdapter.java new file mode 100644 index 00000000..42caaf5c --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/PathAdapter.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.adapter; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.RecyclerView; + +import com.github.gzuliyujiang.filepicker.R; +import com.github.gzuliyujiang.filepicker.contract.OnPathClickedListener; + +import java.io.File; +import java.util.Collections; +import java.util.LinkedList; + +/** + * 文件路径数据适配 + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2017/01/08 01:20 + */ +@SuppressWarnings("unused") +public class PathAdapter extends RecyclerView.Adapter { + private static final String ROOT_HINT = "ROOT"; + private final Context context; + private final LinkedList paths = new LinkedList<>(); + private Drawable arrowIcon = null; + private OnPathClickedListener onPathClickedListener; + + public PathAdapter(@NonNull Context context) { + this.context = context; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + int wrapContent = ViewGroup.LayoutParams.WRAP_CONTENT; + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.HORIZONTAL); + layout.setGravity(Gravity.CENTER_VERTICAL); + layout.setLayoutParams(new ViewGroup.LayoutParams(wrapContent, wrapContent)); + TextView textView = new TextView(context); + LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(wrapContent, wrapContent); + textView.setLayoutParams(tvParams); + textView.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); + int padding = (int) (5 * context.getResources().getDisplayMetrics().density); + textView.setPadding(padding, 0, padding, 0); + layout.addView(textView); + ImageView imageView = new ImageView(context); + int width = (int) (20 * context.getResources().getDisplayMetrics().density); + imageView.setLayoutParams(new LinearLayout.LayoutParams(width, wrapContent)); + layout.addView(imageView); + ViewHolder viewHolder = new ViewHolder(layout); + viewHolder.textView = textView; + viewHolder.imageView = imageView; + return viewHolder; + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { + holder.textView.setText(paths.get(position)); + holder.imageView.setImageDrawable(arrowIcon); + if (onPathClickedListener == null) { + return; + } + holder.itemView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + onPathClickedListener.onPathClicked(position, getPath(position)); + } + }); + } + + @Override + public long getItemId(int position) { + return position; + } + + @Override + public int getItemCount() { + return paths.size(); + } + + public void setArrowIcon(Drawable arrowIcon) { + this.arrowIcon = arrowIcon; + } + + public void updatePath(File file) { + if (arrowIcon == null) { + arrowIcon = ContextCompat.getDrawable(context, R.mipmap.file_picker_arrow); + } + paths.clear(); + String path = file.getAbsolutePath(); + if (!File.separator.equals(path)) { + Collections.addAll(paths, path.substring(path.indexOf(File.separator) + 1) + .split(File.separator)); + } + paths.addFirst(ROOT_HINT); + notifyDataSetChanged(); + } + + public String getPath(int position) { + StringBuilder sb = new StringBuilder(File.separator); + //忽略根目录 + if (position == 0) { + return sb.toString(); + } + for (int i = 1; i <= position; i++) { + sb.append(paths.get(i)).append(File.separator); + } + return sb.toString(); + } + + public final void recycleData() { + paths.clear(); + if (arrowIcon instanceof BitmapDrawable) { + Bitmap homeBitmap = ((BitmapDrawable) arrowIcon).getBitmap(); + if (null != homeBitmap && !homeBitmap.isRecycled()) { + homeBitmap.recycle(); + } + } + } + + public void setOnPathClickedListener(OnPathClickedListener listener) { + onPathClickedListener = listener; + } + +} diff --git a/basepicker/src/main/java/com/github/gzuliyujiang/basepicker/StateDrawable.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/StateDrawable.java similarity index 89% rename from basepicker/src/main/java/com/github/gzuliyujiang/basepicker/StateDrawable.java rename to FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/StateDrawable.java index de39b40c..549a8578 100644 --- a/basepicker/src/main/java/com/github/gzuliyujiang/basepicker/StateDrawable.java +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/StateDrawable.java @@ -11,7 +11,7 @@ * See the Mulan PSL v2 for more details. */ -package com.github.gzuliyujiang.basepicker; +package com.github.gzuliyujiang.filepicker.adapter; import android.content.Context; import android.graphics.Color; @@ -22,6 +22,7 @@ import androidx.annotation.ColorInt; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; /** * 按下状态与普通状态下显示不同的颜色 @@ -30,7 +31,7 @@ * @since 2017/01/01 05:30 */ @SuppressWarnings("unused") -public class StateDrawable extends StateListDrawable { +class StateDrawable extends StateListDrawable { public StateDrawable(@ColorInt int pressedColor) { this(Color.TRANSPARENT, pressedColor); @@ -41,7 +42,7 @@ public StateDrawable(@ColorInt int normalColor, @ColorInt int pressedColor) { } public StateDrawable(@NonNull Context context, @DrawableRes int normalRes, @DrawableRes int pressedRes) { - addState(context.getDrawable(normalRes), context.getDrawable(pressedRes)); + addState(ContextCompat.getDrawable(context, normalRes), ContextCompat.getDrawable(context, pressedRes)); } public StateDrawable(Drawable normal, Drawable pressed) { diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/ViewHolder.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/ViewHolder.java new file mode 100644 index 00000000..c38fe316 --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/adapter/ViewHolder.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.adapter; + +import android.view.View; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 20:47 + */ +public class ViewHolder extends RecyclerView.ViewHolder { + public TextView textView; + public ImageView imageView; + + public ViewHolder(@NonNull View itemView) { + super(itemView); + } + +} \ No newline at end of file diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/annotation/ExplorerMode.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/annotation/ExplorerMode.java new file mode 100644 index 00000000..5ad7d281 --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/annotation/ExplorerMode.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.annotation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 15:28 + */ +@Retention(RetentionPolicy.SOURCE) +public @interface ExplorerMode { + int DIRECTORY = 0; + int FILE = 1; +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/annotation/FileSort.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/annotation/FileSort.java new file mode 100644 index 00000000..4872db3f --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/annotation/FileSort.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.annotation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 14:35 + */ +@Retention(RetentionPolicy.SOURCE) +public @interface FileSort { + int BY_NAME_ASC = 0; + int BY_NAME_DESC = 1; + int BY_TIME_ASC = 2; + int BY_TIME_DESC = 3; + int BY_SIZE_ASC = 4; + int BY_SIZE_DESC = 5; + int BY_EXTENSION_ASC = 6; + int BY_EXTENSION_DESC = 7; +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/contract/OnFileClickedListener.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/contract/OnFileClickedListener.java new file mode 100644 index 00000000..e367071d --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/contract/OnFileClickedListener.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.contract; + +import androidx.annotation.NonNull; + +import java.io.File; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 19:33 + */ +public interface OnFileClickedListener { + + void onFileClicked(@NonNull File file); + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/contract/OnFilePickedListener.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/contract/OnFilePickedListener.java new file mode 100644 index 00000000..b5c2160f --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/contract/OnFilePickedListener.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.contract; + +import androidx.annotation.NonNull; + +import java.io.File; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2015/9/29 + */ +public interface OnFilePickedListener { + + void onFilePicked(@NonNull File file); + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/contract/OnPathClickedListener.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/contract/OnPathClickedListener.java new file mode 100644 index 00000000..f6cb6911 --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/contract/OnPathClickedListener.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.contract; + +import androidx.annotation.NonNull; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 20:15 + */ +public interface OnPathClickedListener { + + void onPathClicked(int position, @NonNull String path); + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/filter/PatternFilter.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/filter/PatternFilter.java new file mode 100644 index 00000000..9a4227e1 --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/filter/PatternFilter.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.filter; + +import androidx.annotation.NonNull; + +import java.io.File; +import java.io.FileFilter; +import java.util.regex.Pattern; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 15:07 + */ +public class PatternFilter implements FileFilter { + private final Pattern pattern; + + public PatternFilter(@NonNull Pattern pattern) { + this.pattern = pattern; + } + + @Override + public boolean accept(File pathname) { + if (pathname == null) { + return false; + } + return pattern.matcher(pathname.getName()).find(); + } + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/filter/SimpleFilter.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/filter/SimpleFilter.java new file mode 100644 index 00000000..72da6e3b --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/filter/SimpleFilter.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.filter; + +import androidx.annotation.Nullable; + +import java.io.File; +import java.io.FileFilter; +import java.util.Arrays; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2021/6/10 15:11 + */ +public class SimpleFilter implements FileFilter { + private final boolean isOnlyDir; + private final String[] allowExtensions; + + public SimpleFilter(boolean isOnlyDir, @Nullable String[] allowExtensions) { + this.isOnlyDir = isOnlyDir; + this.allowExtensions = allowExtensions; + } + + @Override + public boolean accept(File pathname) { + if (pathname == null) { + return false; + } + if (isOnlyDir && pathname.isFile()) { + return false; + } + if (allowExtensions == null || allowExtensions.length == 0) { + return true; + } + //返回当前目录所有以某些扩展名结尾的文件 + String extension = getExtension(pathname.getPath()); + return Arrays.toString(allowExtensions).contains(extension); + } + + private String getExtension(String path) { + if (path == null) { + return ""; + } + int slashPos = path.lastIndexOf(File.separator); + if (slashPos != -1) { + path = path.substring(slashPos); + } + int dotPos = path.lastIndexOf('.'); + if (0 <= dotPos) { + return path.substring(dotPos + 1); + } else { + return ""; + } + } + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortByExtension.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortByExtension.java new file mode 100644 index 00000000..01bb5fba --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortByExtension.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.sort; + +import java.io.File; +import java.util.Comparator; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2014/4/18 + */ +public class SortByExtension implements Comparator { + + @Override + public int compare(File f1, File f2) { + if (f1 == null || f2 == null) { + if (f1 == null) { + return -1; + } else { + return 1; + } + } else { + if (f1.isDirectory() && f2.isFile()) { + return -1; + } else if (f1.isFile() && f2.isDirectory()) { + return 1; + } else { + return f1.getName().compareToIgnoreCase(f2.getName()); + } + } + } + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortByName.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortByName.java new file mode 100644 index 00000000..09d194cb --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortByName.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.sort; + +import java.io.File; +import java.util.Comparator; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2014/4/18 + */ +public class SortByName implements Comparator { + private static final boolean CASE_SENSITIVE = false; + + @Override + public int compare(File f1, File f2) { + if (f1 == null || f2 == null) { + if (f1 == null) { + return -1; + } else { + return 1; + } + } else { + if (f1.isDirectory() && f2.isFile()) { + return -1; + } else if (f1.isFile() && f2.isDirectory()) { + return 1; + } else { + String s1 = f1.getName(); + String s2 = f2.getName(); + if (CASE_SENSITIVE) { + return s1.compareTo(s2); + } else { + return s1.compareToIgnoreCase(s2); + } + } + } + } + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortBySize.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortBySize.java new file mode 100644 index 00000000..832ce3e1 --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortBySize.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.sort; + +import java.io.File; +import java.util.Comparator; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2014/4/18 + */ +public class SortBySize implements Comparator { + + @Override + public int compare(File f1, File f2) { + if (f1 == null || f2 == null) { + if (f1 == null) { + return -1; + } else { + return 1; + } + } else { + if (f1.isDirectory() && f2.isFile()) { + return -1; + } else if (f1.isFile() && f2.isDirectory()) { + return 1; + } else { + if (f1.length() < f2.length()) { + return -1; + } else if (f1.length() > f2.length()) { + return 1; + } else { + return 0; + } + } + } + } + +} diff --git a/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortByTime.java b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortByTime.java new file mode 100644 index 00000000..22dfdbe1 --- /dev/null +++ b/FilePicker/src/main/java/com/github/gzuliyujiang/filepicker/sort/SortByTime.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.filepicker.sort; + +import java.io.File; +import java.util.Comparator; + +/** + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2014/4/18 + */ +public class SortByTime implements Comparator { + + @Override + public int compare(File f1, File f2) { + if (f1 == null || f2 == null) { + if (f1 == null) { + return -1; + } else { + return 1; + } + } else { + if (f1.isDirectory() && f2.isFile()) { + return -1; + } else if (f1.isFile() && f2.isDirectory()) { + return 1; + } else { + if (f1.lastModified() > f2.lastModified()) { + return -1; + } else if (f1.lastModified() < f2.lastModified()) { + return -1; + } else { + return 0; + } + } + } + } + +} diff --git a/FilePicker/src/main/res/layout/file_picker_content.xml b/FilePicker/src/main/res/layout/file_picker_content.xml new file mode 100644 index 00000000..bc63e567 --- /dev/null +++ b/FilePicker/src/main/res/layout/file_picker_content.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_arrow.png b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_arrow.png new file mode 100644 index 00000000..0208fb40 Binary files /dev/null and b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_arrow.png differ diff --git a/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_file.png b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_file.png new file mode 100644 index 00000000..fbcd6d81 Binary files /dev/null and b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_file.png differ diff --git a/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_folder.png b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_folder.png new file mode 100644 index 00000000..a990053d Binary files /dev/null and b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_folder.png differ diff --git a/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_home.png b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_home.png new file mode 100644 index 00000000..94609a66 Binary files /dev/null and b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_home.png differ diff --git a/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_up.png b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_up.png new file mode 100644 index 00000000..52b8dbca Binary files /dev/null and b/FilePicker/src/main/res/mipmap-xxhdpi/file_picker_up.png differ diff --git a/README.md b/README.md index f180179c..22747ea3 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ allprojects { ```groovy dependencies { - implementation 'com.github.gzu-liyujiang:AndroidPicker:basepicker:' + implementation 'com.github.gzu-liyujiang:AndroidPicker:BasePicker:' } ``` @@ -37,7 +37,7 @@ dependencies { ```groovy dependencies { - implementation 'com.github.gzu-liyujiang:AndroidPicker:wheelview:' + implementation 'com.github.gzu-liyujiang:AndroidPicker:WheelView:' } ``` @@ -45,7 +45,7 @@ dependencies { ```groovy dependencies { - implementation 'com.github.gzu-liyujiang:AndroidPicker:wheelpicker:' + implementation 'com.github.gzu-liyujiang:AndroidPicker:WheelPicker:' } ``` @@ -53,7 +53,7 @@ dependencies { ```groovy dependencies { - implementation 'com.github.gzu-liyujiang:AndroidPicker:filepicker:' + implementation 'com.github.gzu-liyujiang:AndroidPicker:FilePicker:' } ``` @@ -61,7 +61,7 @@ dependencies { ```groovy dependencies { - implementation 'com.github.gzu-liyujiang:AndroidPicker:colorpicker:' + implementation 'com.github.gzu-liyujiang:AndroidPicker:ColorPicker:' } ``` @@ -69,7 +69,7 @@ dependencies { ```groovy dependencies { - implementation 'com.github.gzu-liyujiang:AndroidPicker:calendarpicker:' + implementation 'com.github.gzu-liyujiang:AndroidPicker:CalendarPicker:' } ``` diff --git a/WheelPicker/src/main/AndroidManifest.xml b/WheelPicker/src/main/AndroidManifest.xml new file mode 100644 index 00000000..2ac2b188 --- /dev/null +++ b/WheelPicker/src/main/AndroidManifest.xml @@ -0,0 +1,14 @@ + + + diff --git a/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/BirthdayPicker.java b/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/BirthdayPicker.java index 33deec4c..a04fbdd1 100644 --- a/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/BirthdayPicker.java +++ b/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/BirthdayPicker.java @@ -31,6 +31,7 @@ * @since 2019/5/14 14:31 * @since 2.0 */ +@SuppressWarnings("unused") public class BirthdayPicker extends DatePicker { private static final int MAX_AGE = 100; diff --git a/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/NumberPicker.java b/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/NumberPicker.java index fa7d01a1..4e6463d8 100644 --- a/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/NumberPicker.java +++ b/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/NumberPicker.java @@ -32,6 +32,7 @@ * @author 李玉江[QQ:1032694760] * @since 2015/10/24 */ +@SuppressWarnings("unused") public class NumberPicker extends ConfirmPicker { protected NumberWheelLayout wheelLayout; private OnNumberPickedListener onNumberPickedListener; diff --git a/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/OptionPicker.java b/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/OptionPicker.java index bce1fd37..10830f5e 100644 --- a/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/OptionPicker.java +++ b/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/OptionPicker.java @@ -32,7 +32,7 @@ * 单项选择器 * * @author 贵州山野羡民(1032694760@qq.com) - * @see TextProvider + * @see com.github.gzuliyujiang.wheelview.contract.TextProvider * @since 2019/5/8 10:04 */ @SuppressWarnings({"unused"}) diff --git a/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/PhoneCodePicker.java b/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/PhoneCodePicker.java index 7a39a073..1c538483 100644 --- a/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/PhoneCodePicker.java +++ b/WheelPicker/src/main/java/com/github/gzuliyujiang/wheelpicker/PhoneCodePicker.java @@ -29,6 +29,7 @@ * @author 贵州山野羡民(1032694760@qq.com) * @since 2019/5/10 16:44 */ +@SuppressWarnings("unused") public class PhoneCodePicker extends OptionPicker { public PhoneCodePicker(@NonNull Activity activity) { diff --git a/WheelView/README.md b/WheelView/README.md index cc83c535..a3867187 100644 --- a/WheelView/README.md +++ b/WheelView/README.md @@ -1,3 +1,3 @@ -# 滚轮控件 +# 滚轮 仿 IOS 风格的滚轮控件。 diff --git a/WheelView/consumer-rules.pro b/WheelView/consumer-rules.pro new file mode 100644 index 00000000..057cd949 --- /dev/null +++ b/WheelView/consumer-rules.pro @@ -0,0 +1 @@ +# 本库模块专用的混淆规则 diff --git a/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/annotation/ItemTextAlign.java b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/annotation/ItemTextAlign.java new file mode 100644 index 00000000..d69a4f6d --- /dev/null +++ b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/annotation/ItemTextAlign.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.wheelview.annotation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * 滚轮条目文本对齐方式 + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2019/6/19 12:04 + */ +@Retention(RetentionPolicy.SOURCE) +public @interface ItemTextAlign { + int CENTER = 0; + int LEFT = 1; + int RIGHT = 2; +} diff --git a/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/contract/OnWheelChangedListener.java b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/contract/OnWheelChangedListener.java new file mode 100644 index 00000000..1f13a54e --- /dev/null +++ b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/contract/OnWheelChangedListener.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.wheelview.contract; + +import com.github.gzuliyujiang.wheelview.widget.WheelView; + +/** + * 滚轮滑动接口 + * + * @author Florent Champigny + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2019/5/14 20:03 + */ +public interface OnWheelChangedListener { + + /** + * Invoke when scroll stopped + * Will return a distance offset which between current scroll position and + * initial position, this offset is a positive or a negative, positive means + * scrolling from bottom to top, negative means scrolling from top to bottom + * + * @param view wheel view + * @param offset Distance offset which between current scroll position and initial position + */ + void onWheelScrolled(WheelView view, int offset); + + /** + * Invoke when scroll stopped + * This method will be called when wheel stop and return current selected item data's + * position in list + * + * @param view wheel view + * @param position Current selected item data's position in list + */ + void onWheelSelected(WheelView view, int position); + + /** + * Invoke when scroll state changed + * The state always between idle, dragging, and scrolling, this method will + * be called when they switch + * + * @param view wheel view + * @param state {@link WheelView#SCROLL_STATE_IDLE} + * {@link WheelView#SCROLL_STATE_DRAGGING} + * {@link WheelView#SCROLL_STATE_SCROLLING} + *

+ * State only one of the following + * {@link WheelView#SCROLL_STATE_IDLE} + * Express WheelPicker in state of idle + * {@link WheelView#SCROLL_STATE_DRAGGING} + * Express WheelPicker in state of dragging + * {@link WheelView#SCROLL_STATE_SCROLLING} + * Express WheelPicker in state of scrolling + */ + void onWheelScrollStateChanged(WheelView view, int state); + + /** + * Invoke when loop finished + * + * @param view wheel view + */ + void onWheelLoopFinished(WheelView view); + +} diff --git a/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/contract/TextProvider.java b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/contract/TextProvider.java new file mode 100644 index 00000000..55e686c4 --- /dev/null +++ b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/contract/TextProvider.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.wheelview.contract; + +/** + * 提供显示的文本 + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2019/5/14 20:01 + */ +public interface TextProvider { + + /** + * 提供显示的文本 + * + * @return 显示的文本 + */ + String provideText(); + +} + diff --git a/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/contract/WheelFormatter.java b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/contract/WheelFormatter.java new file mode 100644 index 00000000..ed51f0ec --- /dev/null +++ b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/contract/WheelFormatter.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.wheelview.contract; + +import androidx.annotation.NonNull; + +/** + * 滚轮条目显示文本格式化接口 + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2019/5/14 20:02 + */ +public interface WheelFormatter { + + /** + * 格式化滚轮条目显示文本 + * + * @param item 滚轮条目的内容 + * @return 格式化后最终显示的文本 + */ + String formatItem(@NonNull Object item); + +} diff --git a/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/widget/NumberWheelView.java b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/widget/NumberWheelView.java new file mode 100644 index 00000000..708fd703 --- /dev/null +++ b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/widget/NumberWheelView.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.wheelview.widget; + +import android.content.Context; +import android.util.AttributeSet; + +import java.util.ArrayList; +import java.util.List; + +/** + * 数字滚轮控件 + * + * @author 贵州山野羡民(1032694760@qq.com) + * @since 2019/5/13 19:13 + */ +public class NumberWheelView extends WheelView { + + public NumberWheelView(Context context) { + super(context); + } + + public NumberWheelView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public NumberWheelView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } + + @Override + protected List generatePreviewData() { + List data = new ArrayList<>(); + for (int i = 1; i <= 10; i = i + 1) { + data.add(i); + } + return data; + } + + @Deprecated + @Override + public void setData(List data) { + throw new UnsupportedOperationException("Use setRange instead"); + } + + public void setRange(int min, int max, int step) { + int minValue = Math.min(min, max); + int maxValue = Math.max(min, max); + // 指定初始容量,避免OutOfMemory + int capacity = (maxValue - minValue) / step; + List data = new ArrayList<>(capacity); + for (int i = minValue; i <= maxValue; i = i + step) { + data.add(i); + } + super.setData(data); + } + + public void setRange(float min, float max, float step) { + float minValue = Math.min(min, max); + float maxValue = Math.max(min, max); + // 指定初始容量,避免OutOfMemory + int capacity = (int) ((maxValue - minValue) / step); + List data = new ArrayList<>(capacity); + for (float i = minValue; i <= maxValue; i = i + step) { + data.add(i); + } + super.setData(data); + } + +} diff --git a/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/widget/WheelView.java b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/widget/WheelView.java new file mode 100644 index 00000000..048ba302 --- /dev/null +++ b/WheelView/src/main/java/com/github/gzuliyujiang/wheelview/widget/WheelView.java @@ -0,0 +1,1069 @@ +/* + * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<1032694760@qq.com> + * + * The software is licensed under the Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * http://license.coscl.org.cn/MulanPSL2 + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR + * PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package com.github.gzuliyujiang.wheelview.widget; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ValueAnimator; +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Camera; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Matrix; +import android.graphics.Paint; +import android.graphics.Rect; +import android.graphics.Region; +import android.graphics.Typeface; +import android.os.Build; +import android.os.Handler; +import android.text.TextUtils; +import android.util.AttributeSet; +import android.view.MotionEvent; +import android.view.VelocityTracker; +import android.view.View; +import android.view.ViewConfiguration; +import android.widget.Scroller; + +import androidx.annotation.ColorInt; +import androidx.annotation.NonNull; +import androidx.annotation.Px; +import androidx.annotation.StyleRes; + +import com.github.gzuliyujiang.wheelview.R; +import com.github.gzuliyujiang.wheelview.annotation.ItemTextAlign; +import com.github.gzuliyujiang.wheelview.contract.OnWheelChangedListener; +import com.github.gzuliyujiang.wheelview.contract.TextProvider; +import com.github.gzuliyujiang.wheelview.contract.WheelFormatter; + +import java.util.ArrayList; +import java.util.List; + +/** + * 滚轮控件。Adapted from https://github.com/florent37/SingleDateAndTimePicker/.../WheelPicker.java + * + * @author 贵州山野羡民(1032694760@qq.com) + * @see TextProvider + * @see OnWheelChangedListener + * @since 2019/5/8 11:11 + */ +@SuppressWarnings({"unused"}) +public class WheelView extends View implements Runnable { + public static final int SCROLL_STATE_IDLE = 0; + public static final int SCROLL_STATE_DRAGGING = 1; + public static final int SCROLL_STATE_SCROLLING = 2; + + protected List data = new ArrayList<>(); + protected WheelFormatter formatter; + protected Object defaultItem; + protected int visibleItemCount; + protected int defaultItemPosition; + protected int currentPosition; + protected String maxWidthText; + protected int textColor, textColorSelected; + protected int textSize; + protected float indicatorSize; + protected int indicatorColor; + protected int curtainColor; + protected int itemSpace; + protected int textAlign; + protected boolean sameWidthEnabled; + protected boolean indicatorEnabled; + protected boolean curtainEnabled; + protected boolean atmosphericEnabled; + protected boolean cyclicEnabled; + protected boolean curvedEnabled; + protected int curvedMaxAngle = 90; + + private final Handler handler = new Handler(); + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.LINEAR_TEXT_FLAG); + private final Scroller scroller; + private VelocityTracker tracker; + private OnWheelChangedListener onWheelChangedListener; + private final Rect rectDrawn = new Rect(); + private final Rect rectIndicatorHead = new Rect(); + private final Rect rectIndicatorFoot = new Rect(); + private final Rect rectCurrentItem = new Rect(); + private final Camera camera = new Camera(); + private final Matrix matrixRotate = new Matrix(); + private final Matrix matrixDepth = new Matrix(); + private int lastScrollPosition; + private int drawnItemCount; + private int halfDrawnItemCount; + private int textMaxWidth, textMaxHeight; + private int itemHeight, halfItemHeight; + private int halfWheelHeight; + private int minFlingYCoordinate, maxFlingYCoordinate; + private int wheelCenterXCoordinate, wheelCenterYCoordinate; + private int drawnCenterXCoordinate, drawnCenterYCoordinate; + private int scrollOffsetYCoordinate; + private int lastPointYCoordinate; + private int downPointYCoordinate; + private final int minimumVelocity; + private final int maximumVelocity; + private final int touchSlop; + private boolean isClick; + private boolean isForceFinishScroll; + private final AttributeSet attrs; + + public WheelView(Context context) { + this(context, null); + } + + public WheelView(Context context, AttributeSet attrs) { + this(context, attrs, R.attr.WheelStyle); + } + + public WheelView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + this.attrs = attrs; + initAttrs(context, attrs, defStyleAttr, R.style.WheelDefault); + updateVisibleItemCount(); + paint.setTextSize(textSize); + scroller = new Scroller(context); + ViewConfiguration configuration = ViewConfiguration.get(context); + minimumVelocity = configuration.getScaledMinimumFlingVelocity(); + maximumVelocity = configuration.getScaledMaximumFlingVelocity(); + touchSlop = configuration.getScaledTouchSlop(); + if (isInEditMode()) { + setData(generatePreviewData()); + } + } + + public void setStyle(@StyleRes int style) { + if (attrs == null) { + throw new RuntimeException("Please use " + getClass().getSimpleName() + " in xml"); + } + initAttrs(getContext(), attrs, R.attr.WheelStyle, style); + requestLayout(); + invalidate(); + } + + private void initAttrs(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + if (attrs == null) { + textSize = (int) (15 * context.getResources().getDisplayMetrics().scaledDensity); + visibleItemCount = 5; + defaultItemPosition = 0; + sameWidthEnabled = false; + maxWidthText = ""; + textColorSelected = 0xFF000000; + textColor = 0xFF888888; + itemSpace = (int) (20 * context.getResources().getDisplayMetrics().density); + cyclicEnabled = false; + indicatorEnabled = true; + indicatorColor = 0xFFC9C9C9; + indicatorSize = 1 * context.getResources().getDisplayMetrics().density; + curtainEnabled = false; + curtainColor = 0xFFFFFFFF; + atmosphericEnabled = false; + curvedEnabled = false; + curvedMaxAngle = 90; + textAlign = ItemTextAlign.CENTER; + return; + } + TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.WheelView, + defStyleAttr, defStyleRes); + onAttributeSet(context, typedArray); + typedArray.recycle(); + } + + protected void onAttributeSet(@NonNull Context context, @NonNull TypedArray typedArray) { + float density = context.getResources().getDisplayMetrics().density; + float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity; + textSize = typedArray.getDimensionPixelSize(R.styleable.WheelView_wheel_itemTextSize, + (int) (15 * scaledDensity)); + visibleItemCount = typedArray.getInt(R.styleable.WheelView_wheel_visibleItemCount, 5); + sameWidthEnabled = typedArray.getBoolean(R.styleable.WheelView_wheel_sameWidthEnabled, false); + maxWidthText = typedArray.getString(R.styleable.WheelView_wheel_maxWidthText); + textColorSelected = typedArray.getColor(R.styleable.WheelView_wheel_itemTextColorSelected, 0xFF000000); + textColor = typedArray.getColor(R.styleable.WheelView_wheel_itemTextColor, 0xFF888888); + itemSpace = typedArray.getDimensionPixelSize(R.styleable.WheelView_wheel_itemSpace, (int) (20 * density)); + cyclicEnabled = typedArray.getBoolean(R.styleable.WheelView_wheel_cyclicEnabled, false); + indicatorEnabled = typedArray.getBoolean(R.styleable.WheelView_wheel_indicatorEnabled, true); + indicatorColor = typedArray.getColor(R.styleable.WheelView_wheel_indicatorColor, 0xFFC9C9C9); + indicatorSize = typedArray.getDimension(R.styleable.WheelView_wheel_indicatorSize, 1 * density); + curtainEnabled = typedArray.getBoolean(R.styleable.WheelView_wheel_curtainEnabled, false); + curtainColor = typedArray.getColor(R.styleable.WheelView_wheel_curtainColor, 0xFFFFFFFF); + atmosphericEnabled = typedArray.getBoolean(R.styleable.WheelView_wheel_atmosphericEnabled, false); + curvedEnabled = typedArray.getBoolean(R.styleable.WheelView_wheel_curvedEnabled, false); + curvedMaxAngle = typedArray.getInteger(R.styleable.WheelView_wheel_curvedMaxAngle, 90); + textAlign = typedArray.getInt(R.styleable.WheelView_wheel_itemTextAlign, ItemTextAlign.CENTER); + } + + protected List generatePreviewData() { + List data = new ArrayList<>(); + data.add("贵州穿青人"); + data.add("大定府羡民"); + data.add("不在五十六个民族之内"); + data.add("已识别待定民族"); + data.add("穿青山魈人马"); + data.add("李裕江"); + return data; + } + + private void updateVisibleItemCount() { + final int minCount = 2; + if (visibleItemCount < minCount) { + throw new ArithmeticException("Visible item count can not be less than " + minCount); + } + + int evenNumberFlag = 2; + if (visibleItemCount % evenNumberFlag == 0) { + visibleItemCount += 1; + } + drawnItemCount = visibleItemCount + 2; + halfDrawnItemCount = drawnItemCount / 2; + } + + private void computeTextWidthAndHeight() { + textMaxWidth = textMaxHeight = 0; + if (sameWidthEnabled) { + textMaxWidth = (int) paint.measureText(formatItem(0)); + } else if (!TextUtils.isEmpty(maxWidthText)) { + textMaxWidth = (int) paint.measureText(maxWidthText); + } else { + // 未指定最宽的文本,须遍历测量查找最宽的作为基准 + int itemCount = getItemCount(); + for (int i = 0; i < itemCount; ++i) { + int width = (int) paint.measureText(formatItem(i)); + textMaxWidth = Math.max(textMaxWidth, width); + } + } + Paint.FontMetrics metrics = paint.getFontMetrics(); + textMaxHeight = (int) (metrics.bottom - metrics.top); + } + + public int getItemCount() { + return data.size(); + } + + public Object getItem(int position) { + final int size = data.size(); + if (size == 0) { + return null; + } + int index = (position + size) % size; + if (index >= 0 && index <= size - 1) { + return data.get(index); + } + return null; + } + + public int getPosition(Object item) { + if (item == null) { + return 0; + } + return data.indexOf(item); + } + + public int getCurrentPosition() { + return currentPosition; + } + + public Object getCurrentItem() { + return getItem(currentPosition); + } + + public int getVisibleItemCount() { + return visibleItemCount; + } + + public void setVisibleItemCount(int count) { + visibleItemCount = count; + updateVisibleItemCount(); + requestLayout(); + } + + public boolean isCyclicEnabled() { + return cyclicEnabled; + } + + public void setCyclicEnabled(boolean isCyclic) { + this.cyclicEnabled = isCyclic; + computeFlingLimitYCoordinate(); + invalidate(); + } + + public void setOnWheelChangedListener(OnWheelChangedListener listener) { + onWheelChangedListener = listener; + } + + public void setFormatter(WheelFormatter formatter) { + this.formatter = formatter; + } + + public List getData() { + return data; + } + + public void setData(List newData) { + if (newData == null) { + newData = new ArrayList<>(); + } + data = newData; + notifyDataSetChanged(); + } + + public void setDefaultValue(Object value) { + if (value == null) { + return; + } + int position = 0; + for (Object item : data) { + if (item.equals(value)) { + break; + } + if (item instanceof TextProvider) { + String text = ((TextProvider) item).provideText(); + if (text.equals(value)) { + break; + } + } + position++; + } + setDefaultPosition(position); + } + + public void setDefaultPosition(int position) { + position = Math.min(position, getItemCount() - 1); + position = Math.max(position, 0); + defaultItem = getItem(position); + defaultItemPosition = position; + currentPosition = position; + scrollOffsetYCoordinate = 0; + computeFlingLimitYCoordinate(); + requestLayout(); + invalidate(); + } + + public boolean isSameWidthEnabled() { + return sameWidthEnabled; + } + + public void setSameWidthEnabled(boolean sameWidthEnabled) { + this.sameWidthEnabled = sameWidthEnabled; + computeTextWidthAndHeight(); + requestLayout(); + invalidate(); + } + + public String getMaxWidthText() { + return maxWidthText; + } + + public void setMaxWidthText(String text) { + if (null == text) { + throw new NullPointerException("Maximum width text can not be null!"); + } + maxWidthText = text; + computeTextWidthAndHeight(); + requestLayout(); + invalidate(); + } + + @ColorInt + public int getSelectedTextColor() { + return textColorSelected; + } + + public void setSelectedTextColor(@ColorInt int color) { + textColorSelected = color; + computeCurrentItemRect(); + invalidate(); + } + + @ColorInt + public int getTextColor() { + return textColor; + } + + public void setTextColor(@ColorInt int color) { + textColor = color; + invalidate(); + } + + @Px + public int getTextSize() { + return textSize; + } + + public void setTextSize(@Px int size) { + textSize = size; + paint.setTextSize(textSize); + computeTextWidthAndHeight(); + requestLayout(); + invalidate(); + } + + @Px + public int getItemSpace() { + return itemSpace; + } + + public void setItemSpace(@Px int space) { + itemSpace = space; + requestLayout(); + invalidate(); + } + + public boolean isIndicatorEnabled() { + return indicatorEnabled; + } + + public void setIndicatorEnabled(boolean indicatorEnabled) { + this.indicatorEnabled = indicatorEnabled; + computeIndicatorRect(); + invalidate(); + } + + @Px + public float getIndicatorSize() { + return indicatorSize; + } + + public void setIndicatorSize(@Px float size) { + indicatorSize = size; + computeIndicatorRect(); + invalidate(); + } + + @ColorInt + public int getIndicatorColor() { + return indicatorColor; + } + + public void setIndicatorColor(@ColorInt int color) { + indicatorColor = color; + invalidate(); + } + + public boolean isCurtainEnabled() { + return curtainEnabled; + } + + public void setCurtainEnabled(boolean curtainEnabled) { + this.curtainEnabled = curtainEnabled; + computeCurrentItemRect(); + invalidate(); + } + + @ColorInt + public int getCurtainColor() { + return curtainColor; + } + + public void setCurtainColor(@ColorInt int color) { + curtainColor = color; + invalidate(); + } + + public boolean isAtmosphericEnabled() { + return atmosphericEnabled; + } + + public void setAtmosphericEnabled(boolean atmosphericEnabled) { + this.atmosphericEnabled = atmosphericEnabled; + invalidate(); + } + + public boolean isCurvedEnabled() { + return curvedEnabled; + } + + public void setCurvedEnabled(boolean isCurved) { + this.curvedEnabled = isCurved; + requestLayout(); + invalidate(); + } + + public int getCurvedMaxAngle() { + return curvedMaxAngle; + } + + public void setCurvedMaxAngle(int curvedMaxAngle) { + this.curvedMaxAngle = curvedMaxAngle; + requestLayout(); + invalidate(); + } + + @ItemTextAlign + public int getTextAlign() { + return textAlign; + } + + public void setTextAlign(@ItemTextAlign int align) { + textAlign = align; + updatePaintTextAlign(); + computeDrawnCenterCoordinate(); + invalidate(); + } + + private void updatePaintTextAlign() { + switch (textAlign) { + case ItemTextAlign.LEFT: + paint.setTextAlign(Paint.Align.LEFT); + break; + case ItemTextAlign.RIGHT: + paint.setTextAlign(Paint.Align.RIGHT); + break; + case ItemTextAlign.CENTER: + default: + paint.setTextAlign(Paint.Align.CENTER); + break; + } + } + + public Typeface getTypeface() { + if (null != paint) { + return paint.getTypeface(); + } + return null; + } + + public void setTypeface(Typeface typeface) { + if (paint == null || typeface == null) { + return; + } + paint.setTypeface(typeface); + computeTextWidthAndHeight(); + requestLayout(); + invalidate(); + } + + public void notifyDataSetChanged() { + defaultItem = getItem(0); + defaultItemPosition = 0; + currentPosition = 0; + scrollOffsetYCoordinate = 0; + updatePaintTextAlign(); + computeTextWidthAndHeight(); + computeFlingLimitYCoordinate(); + requestLayout(); + invalidate(); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + final int modeWidth = MeasureSpec.getMode(widthMeasureSpec); + final int modeHeight = MeasureSpec.getMode(heightMeasureSpec); + final int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); + final int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); + // Correct sizes of original content + int resultWidth = textMaxWidth; + int resultHeight = textMaxHeight * visibleItemCount + itemSpace * (visibleItemCount - 1); + // Correct view sizes again if curved is enable + if (curvedEnabled) { + resultHeight = (int) (2 * resultHeight / Math.PI); + } + // Consideration padding influence the view sizes + resultWidth += getPaddingLeft() + getPaddingRight(); + resultHeight += getPaddingTop() + getPaddingBottom(); + // Consideration sizes of parent can influence the view sizes + resultWidth = measureSize(modeWidth, sizeWidth, resultWidth); + resultHeight = measureSize(modeHeight, sizeHeight, resultHeight); + setMeasuredDimension(resultWidth, resultHeight); + } + + private int measureSize(int mode, int sizeExpect, int sizeActual) { + int realSize; + if (mode == MeasureSpec.EXACTLY) { + realSize = sizeExpect; + } else { + realSize = sizeActual; + if (mode == MeasureSpec.AT_MOST) { + realSize = Math.min(realSize, sizeExpect); + } + } + return realSize; + } + + @Override + protected void onSizeChanged(int w, int h, int ow, int oh) { + // Set content region + rectDrawn.set(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), + getHeight() - getPaddingBottom()); + // Get the center coordinates of content region + wheelCenterXCoordinate = rectDrawn.centerX(); + wheelCenterYCoordinate = rectDrawn.centerY(); + // Correct item drawn center + computeDrawnCenterCoordinate(); + halfWheelHeight = rectDrawn.height() / 2; + itemHeight = rectDrawn.height() / visibleItemCount; + halfItemHeight = itemHeight / 2; + // Initialize fling max Y-coordinates + computeFlingLimitYCoordinate(); + // Correct region of indicator + computeIndicatorRect(); + // Correct region of current select item + computeCurrentItemRect(); + } + + private void computeDrawnCenterCoordinate() { + switch (textAlign) { + case ItemTextAlign.LEFT: + drawnCenterXCoordinate = rectDrawn.left; + break; + case ItemTextAlign.RIGHT: + drawnCenterXCoordinate = rectDrawn.right; + break; + case ItemTextAlign.CENTER: + default: + drawnCenterXCoordinate = wheelCenterXCoordinate; + break; + } + drawnCenterYCoordinate = (int) (wheelCenterYCoordinate - + ((paint.ascent() + paint.descent()) / 2)); + } + + private void computeFlingLimitYCoordinate() { + int currentItemOffset = defaultItemPosition * itemHeight; + minFlingYCoordinate = cyclicEnabled ? Integer.MIN_VALUE + : -itemHeight * (getItemCount() - 1) + currentItemOffset; + maxFlingYCoordinate = cyclicEnabled ? Integer.MAX_VALUE : currentItemOffset; + } + + private void computeIndicatorRect() { + if (!indicatorEnabled) { + return; + } + int halfIndicatorSize = (int) (indicatorSize / 2f); + int indicatorHeadCenterYCoordinate = wheelCenterYCoordinate + halfItemHeight; + int indicatorFootCenterYCoordinate = wheelCenterYCoordinate - halfItemHeight; + rectIndicatorHead.set(rectDrawn.left, indicatorHeadCenterYCoordinate - halfIndicatorSize, + rectDrawn.right, indicatorHeadCenterYCoordinate + halfIndicatorSize); + rectIndicatorFoot.set(rectDrawn.left, indicatorFootCenterYCoordinate - halfIndicatorSize, + rectDrawn.right, indicatorFootCenterYCoordinate + halfIndicatorSize); + } + + private void computeCurrentItemRect() { + if (!curtainEnabled && textColorSelected == -1) { + return; + } + rectCurrentItem.set(rectDrawn.left, wheelCenterYCoordinate - halfItemHeight, + rectDrawn.right, wheelCenterYCoordinate + halfItemHeight); + } + + @Override + protected void onDraw(Canvas canvas) { + if (null != onWheelChangedListener) { + onWheelChangedListener.onWheelScrolled(this, scrollOffsetYCoordinate); + } + if (itemHeight - halfDrawnItemCount <= 0) { + return; + } + drawAllItemText(canvas); + drawCurtain(canvas); + drawIndicator(canvas); + } + + private void drawAllItemText(Canvas canvas) { + int drawnDataStartPos = -1 * scrollOffsetYCoordinate / itemHeight - halfDrawnItemCount; + for (int drawnDataPosition = drawnDataStartPos + defaultItemPosition, + drawnOffsetPos = -1 * halfDrawnItemCount; + drawnDataPosition < drawnDataStartPos + defaultItemPosition + drawnItemCount; + drawnDataPosition++, drawnOffsetPos++) { + + paint.setColor(textColor); + paint.setStyle(Paint.Style.FILL); + + int drawnItemCenterYCoordinate = drawnCenterYCoordinate + (drawnOffsetPos * itemHeight) + + scrollOffsetYCoordinate % itemHeight; + + int centerYCoordinateAbs = Math.abs(drawnCenterYCoordinate - drawnItemCenterYCoordinate); + // Correct ratio of item's drawn center to wheel center + float ratio = (drawnCenterYCoordinate - centerYCoordinateAbs - rectDrawn.top) * 1f / + (drawnCenterYCoordinate - rectDrawn.top); + float degree = computeDegree(drawnItemCenterYCoordinate, ratio); + float distanceToCenter = computeYCoordinateAtAngle(degree); + + if (curvedEnabled) { + int transXCoordinate = wheelCenterXCoordinate; + switch (textAlign) { + case ItemTextAlign.LEFT: + transXCoordinate = rectDrawn.left; + break; + case ItemTextAlign.RIGHT: + transXCoordinate = rectDrawn.right; + break; + case ItemTextAlign.CENTER: + default: + break; + } + float transYCoordinate = wheelCenterYCoordinate - distanceToCenter; + + camera.save(); + camera.rotateX(degree); + camera.getMatrix(matrixRotate); + camera.restore(); + matrixRotate.preTranslate(-transXCoordinate, -transYCoordinate); + matrixRotate.postTranslate(transXCoordinate, transYCoordinate); + + camera.save(); + camera.translate(0, 0, computeDepth(degree)); + camera.getMatrix(matrixDepth); + camera.restore(); + matrixDepth.preTranslate(-transXCoordinate, -transYCoordinate); + matrixDepth.postTranslate(transXCoordinate, transYCoordinate); + matrixRotate.postConcat(matrixDepth); + } + + computeAndSetAtmospheric(centerYCoordinateAbs); + // Correct item's drawn center Y coordinate base on curved state + float drawCenterYCoordinate = curvedEnabled ? drawnCenterYCoordinate - distanceToCenter + : drawnItemCenterYCoordinate; + String data = obtainItemText(drawnDataPosition); + if (paint.measureText(data) - getMeasuredWidth() > 0) { + // 超出控件宽度则省略部分文字 + data = data.substring(0, data.length() - 3) + "..."; + } + drawItemText(canvas, data, drawCenterYCoordinate); + } + } + + private void drawItemText(Canvas canvas, String data, float drawCenterYCoordinate) { + // Judges need to draw different color for current item or not + if (textColorSelected == -1) { + canvas.save(); + canvas.clipRect(rectDrawn); + if (curvedEnabled) { + canvas.concat(matrixRotate); + } + canvas.drawText(data, drawnCenterXCoordinate, drawCenterYCoordinate, paint); + canvas.restore(); + return; + } + + canvas.save(); + if (curvedEnabled) { + canvas.concat(matrixRotate); + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + canvas.clipOutRect(rectCurrentItem); + } else { + canvas.clipRect(rectCurrentItem, Region.Op.DIFFERENCE); + } + canvas.drawText(data, drawnCenterXCoordinate, drawCenterYCoordinate, paint); + canvas.restore(); + + paint.setColor(textColorSelected); + canvas.save(); + if (curvedEnabled) { + canvas.concat(matrixRotate); + } + canvas.clipRect(rectCurrentItem); + canvas.drawText(data, drawnCenterXCoordinate, drawCenterYCoordinate, paint); + canvas.restore(); + } + + private float computeDegree(int drawnItemCenterYCoordinate, float ratio) { + // Correct unit + int unit = 0; + if (drawnItemCenterYCoordinate > drawnCenterYCoordinate) { + unit = 1; + } else if (drawnItemCenterYCoordinate < drawnCenterYCoordinate) { + unit = -1; + } + return clamp((-(1 - ratio) * curvedMaxAngle * unit), -curvedMaxAngle, curvedMaxAngle); + } + + private float clamp(float value, float min, float max) { + if (value < min) { + return min; + } + return Math.min(value, max); + } + + private String obtainItemText(int drawnDataPosition) { + String data = ""; + final int itemCount = getItemCount(); + if (cyclicEnabled) { + if (itemCount != 0) { + int actualPosition = drawnDataPosition % itemCount; + actualPosition = actualPosition < 0 ? (actualPosition + itemCount) : actualPosition; + data = formatItem(actualPosition); + } + } else { + if (isPositionInRange(drawnDataPosition, itemCount)) { + data = formatItem(drawnDataPosition); + } + } + return data; + } + + public String formatItem(int position) { + Object item = getItem(position); + if (item instanceof TextProvider) { + return ((TextProvider) item).provideText(); + } + if (formatter != null) { + return formatter.formatItem(item); + } + return item.toString(); + } + + private void computeAndSetAtmospheric(int abs) { + if (atmosphericEnabled) { + int alpha = (int) ((drawnCenterYCoordinate - abs) * 1.0F / drawnCenterYCoordinate * 255); + alpha = Math.max(alpha, 0); + paint.setAlpha(alpha); + } + } + + private void drawCurtain(Canvas canvas) { + // Need to draw curtain or not + if (curtainEnabled) { + int red = Color.red(curtainColor); + int green = Color.green(curtainColor); + int blue = Color.blue(curtainColor); + paint.setColor(Color.argb(128, red, green, blue)); + paint.setStyle(Paint.Style.FILL); + canvas.drawRect(rectCurrentItem, paint); + } + } + + private void drawIndicator(Canvas canvas) { + // Need to draw indicator or not + if (indicatorEnabled) { + paint.setColor(indicatorColor); + paint.setStyle(Paint.Style.FILL); + canvas.drawRect(rectIndicatorHead, paint); + canvas.drawRect(rectIndicatorFoot, paint); + } + } + + private boolean isPositionInRange(int position, int itemCount) { + return position >= 0 && position < itemCount; + } + + private float computeYCoordinateAtAngle(float degree) { + // Compute y-coordinate for item at degree. + return sinDegree(degree) / sinDegree(curvedMaxAngle) * halfWheelHeight; + } + + private float sinDegree(float degree) { + return (float) Math.sin(Math.toRadians(degree)); + } + + private int computeDepth(float degree) { + return (int) (halfWheelHeight - Math.cos(Math.toRadians(degree)) * halfWheelHeight); + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + if (isEnabled()) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + handleActionDown(event); + break; + case MotionEvent.ACTION_MOVE: + handleActionMove(event); + break; + case MotionEvent.ACTION_UP: + handleActionUp(event); + break; + case MotionEvent.ACTION_CANCEL: + handleActionCancel(event); + break; + default: + break; + } + } + if (isClick) { + //onTouchEvent should call performClick when a click is detected + performClick(); + } + return true; + } + + private void handleActionDown(MotionEvent event) { + if (null != getParent()) { + getParent().requestDisallowInterceptTouchEvent(true); + } + obtainOrClearTracker(); + tracker.addMovement(event); + if (!scroller.isFinished()) { + scroller.abortAnimation(); + isForceFinishScroll = true; + } + downPointYCoordinate = lastPointYCoordinate = (int) event.getY(); + } + + private void handleActionMove(MotionEvent event) { + int endPoint = computeDistanceToEndPoint(scroller.getFinalY() % itemHeight); + if (Math.abs(downPointYCoordinate - event.getY()) < touchSlop && endPoint > 0) { + isClick = true; + return; + } + isClick = false; + if (null != tracker) { + tracker.addMovement(event); + } + if (null != onWheelChangedListener) { + onWheelChangedListener.onWheelScrollStateChanged(this, SCROLL_STATE_DRAGGING); + } + // Scroll WheelPicker's content + float move = event.getY() - lastPointYCoordinate; + if (Math.abs(move) < 1) { + return; + } + scrollOffsetYCoordinate += move; + lastPointYCoordinate = (int) event.getY(); + invalidate(); + } + + private void handleActionUp(MotionEvent event) { + if (null != getParent()) { + getParent().requestDisallowInterceptTouchEvent(false); + } + if (isClick) { + return; + } + int yVelocity = 0; + if (null != tracker) { + tracker.addMovement(event); + tracker.computeCurrentVelocity(1000, maximumVelocity); + yVelocity = (int) tracker.getYVelocity(); + } + + // Judge scroll or fling base on current velocity + isForceFinishScroll = false; + if (Math.abs(yVelocity) > minimumVelocity) { + scroller.fling(0, scrollOffsetYCoordinate, 0, yVelocity, 0, + 0, minFlingYCoordinate, maxFlingYCoordinate); + int endPoint = computeDistanceToEndPoint(scroller.getFinalY() % itemHeight); + scroller.setFinalY(scroller.getFinalY() + endPoint); + } else { + int endPoint = computeDistanceToEndPoint(scrollOffsetYCoordinate % itemHeight); + scroller.startScroll(0, scrollOffsetYCoordinate, 0, endPoint); + } + // Correct coordinates + if (!cyclicEnabled) { + if (scroller.getFinalY() > maxFlingYCoordinate) { + scroller.setFinalY(maxFlingYCoordinate); + } else if (scroller.getFinalY() < minFlingYCoordinate) { + scroller.setFinalY(minFlingYCoordinate); + } + } + handler.post(this); + cancelTracker(); + } + + private void handleActionCancel(MotionEvent event) { + if (null != getParent()) { + getParent().requestDisallowInterceptTouchEvent(false); + } + cancelTracker(); + } + + private void obtainOrClearTracker() { + if (null == tracker) { + tracker = VelocityTracker.obtain(); + } else { + tracker.clear(); + } + } + + private void cancelTracker() { + if (null != tracker) { + tracker.recycle(); + tracker = null; + } + } + + @Override + public boolean performClick() { + return super.performClick(); + } + + private int computeDistanceToEndPoint(int remainder) { + if (Math.abs(remainder) > halfItemHeight) { + if (scrollOffsetYCoordinate < 0) { + return -itemHeight - remainder; + } else { + return itemHeight - remainder; + } + } else { + return -1 * remainder; + } + } + + @Override + public void run() { + if (itemHeight == 0) { + return; + } + int itemCount = getItemCount(); + if (itemCount == 0) { + return; + } + if (scroller.isFinished() && !isForceFinishScroll) { + int position = computePosition(itemCount); + position = position < 0 ? position + itemCount : position; + currentPosition = position; + if (null != onWheelChangedListener) { + onWheelChangedListener.onWheelSelected(this, position); + onWheelChangedListener.onWheelScrollStateChanged(this, SCROLL_STATE_IDLE); + } + postInvalidate(); + return; + } + // Scroll not finished + if (scroller.computeScrollOffset()) { + if (null != onWheelChangedListener) { + onWheelChangedListener.onWheelScrollStateChanged(this, SCROLL_STATE_SCROLLING); + } + scrollOffsetYCoordinate = scroller.getCurrY(); + int position = computePosition(itemCount); + if (lastScrollPosition != position) { + if (position == 0 && lastScrollPosition == itemCount - 1) { + if (null != onWheelChangedListener) { + onWheelChangedListener.onWheelLoopFinished(this); + } + } + lastScrollPosition = position; + } + postInvalidate(); + handler.postDelayed(this, 16); + } + } + + private int computePosition(int itemCount) { + return (-1 * scrollOffsetYCoordinate / itemHeight + defaultItemPosition) % itemCount; + } + + public final void scrollTo(final int position) { + if (position == currentPosition) { + return; + } + final int differencesLines = currentPosition - position; + final int newScrollOffsetYCoordinate = scrollOffsetYCoordinate + (differencesLines * itemHeight); + ValueAnimator animator = ValueAnimator.ofInt(scrollOffsetYCoordinate, newScrollOffsetYCoordinate); + animator.setDuration(300); + animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { + @Override + public void onAnimationUpdate(ValueAnimator animation) { + scrollOffsetYCoordinate = (int) animation.getAnimatedValue(); + invalidate(); + } + }); + animator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + currentPosition = position; + } + }); + animator.start(); + } + +} diff --git a/app/src/main/java/cn/qqtheme/androidpicker/AddressInitTask.java b/app/src/main/java/cn/qqtheme/androidpicker/AddressInitTask.java deleted file mode 100644 index aeb6d54c..00000000 --- a/app/src/main/java/cn/qqtheme/androidpicker/AddressInitTask.java +++ /dev/null @@ -1,144 +0,0 @@ -package cn.qqtheme.androidpicker; - -import android.app.Activity; -import android.app.ProgressDialog; -import android.os.AsyncTask; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.List; - -import androidx.annotation.WorkerThread; -import cn.qqtheme.framework.entity.City; -import cn.qqtheme.framework.entity.County; -import cn.qqtheme.framework.entity.Province; -import cn.qqtheme.framework.util.ConvertUtils; - -/** - * 获取地址数据 - * - * @author 李玉江[QQ:1032694760] - * @since 2017/10/13 - */ -public class AddressInitTask extends AsyncTask> { - private WeakReference activityReference;// 2018/2/1 StaticFieldLeak - private ProgressDialog dialog; - private InitCallback callback; - private ArrayList provinces; - - public AddressInitTask(Activity activity, InitCallback callback) { - this.activityReference = new WeakReference<>(activity); - this.callback = callback; - } - - @Override - protected void onPreExecute() { - Activity activity = activityReference.get(); - if (activity != null) { - dialog = ProgressDialog.show(activity, null, "正在初始化数据...", true, true); - } - } - - @Override - protected ArrayList doInBackground(Void... params) { - Activity activity = activityReference.get(); - if (activity == null) { - return null; - } - try { - String data = ConvertUtils.toString(activity.getAssets().open("city.txt")); - return parseData(data); - } catch (java.io.IOException e) { - e.printStackTrace(); - return null; - } - } - - @Override - protected void onPostExecute(ArrayList result) { - if (dialog != null) { - dialog.dismiss(); - } - if (result == null || result.size() == 0) { - callback.onDataInitFailure(); - } else { - callback.onDataInitSuccess(result); - } - } - - @WorkerThread - private ArrayList parseData(String data) { - if (provinces != null && provinces.size() > 0) { - return provinces; - } - provinces = new ArrayList<>(); - String[] fullCodeAndNames = data.split(";"); - for (String fullCodeAndName : fullCodeAndNames) { - String[] codeAndName = fullCodeAndName.split(","); - if (codeAndName.length != 2) { - continue; - } - String code = codeAndName[0]; - String name = codeAndName[1]; - if (code.substring(2, 6).equals("0000")) { - //省份 - Province province = new Province(); - province.setAreaId(code); - province.setAreaName(name); - province.setCities(new ArrayList()); - provinces.add(province); - } else if (code.substring(4, 6).equals("00")) { - //地市 - Province province = findProvinceByCode(code.substring(0, 2)); - if (province != null) { - City city = new City(); - city.setAreaId(code); - city.setAreaName(name); - city.setCounties(new ArrayList()); - province.getCities().add(city); - } - } else { - //区县 - City city = findCityByCode(code.substring(0, 2), code.substring(2, 4)); - if (city != null) { - County county = new County(); - county.setAreaId(code); - county.setAreaName(name); - city.getCounties().add(county); - } - } - } - return provinces; - } - - private Province findProvinceByCode(String provinceCode) { - for (Province province : provinces) { - if (province.getAreaId().substring(0, 2).equals(provinceCode)) { - return province; - } - } - return null; - } - - private City findCityByCode(String provinceCode, String cityCode) { - for (Province province : provinces) { - List cities = province.getCities(); - for (City city : cities) { - if (province.getAreaId().substring(0, 2).equals(provinceCode) && - city.getAreaId().substring(2, 4).equals(cityCode)) { - return city; - } - } - } - return null; - } - - public interface InitCallback { - - void onDataInitFailure(); - - void onDataInitSuccess(ArrayList provinces); - - } - -} diff --git a/app/src/main/java/cn/qqtheme/androidpicker/AddressPickTask.java b/app/src/main/java/cn/qqtheme/androidpicker/AddressPickTask.java deleted file mode 100644 index c542ef01..00000000 --- a/app/src/main/java/cn/qqtheme/androidpicker/AddressPickTask.java +++ /dev/null @@ -1,120 +0,0 @@ -package cn.qqtheme.androidpicker; - -import android.app.Activity; -import android.app.ProgressDialog; -import android.os.AsyncTask; - -import com.alibaba.fastjson.JSON; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; - -import cn.qqtheme.framework.entity.Province; -import cn.qqtheme.framework.picker.AddressPicker; -import cn.qqtheme.framework.util.ConvertUtils; - -/** - * 获取地址数据并显示地址选择器 - * - * @author 李玉江[QQ:1032694760] - * @since 2015/12/15 - */ -public class AddressPickTask extends AsyncTask> { - private WeakReference activityReference;// 2018/6/1 StaticFieldLeak - private ProgressDialog dialog; - private Callback callback; - private String selectedProvince = "", selectedCity = "", selectedCounty = ""; - private boolean hideProvince = false; - private boolean hideCounty = false; - - public AddressPickTask(Activity activity) { - this.activityReference = new WeakReference<>(activity); - } - - public void setHideProvince(boolean hideProvince) { - this.hideProvince = hideProvince; - } - - public void setHideCounty(boolean hideCounty) { - this.hideCounty = hideCounty; - } - - public void setCallback(Callback callback) { - this.callback = callback; - } - - @Override - protected void onPreExecute() { - Activity activity = activityReference.get(); - if (activity == null) { - return; - } - dialog = ProgressDialog.show(activity, null, "正在初始化数据...", true, true); - } - - @Override - protected ArrayList doInBackground(String... params) { - if (params != null) { - switch (params.length) { - case 1: - selectedProvince = params[0]; - break; - case 2: - selectedProvince = params[0]; - selectedCity = params[1]; - break; - case 3: - selectedProvince = params[0]; - selectedCity = params[1]; - selectedCounty = params[2]; - break; - default: - break; - } - } - ArrayList data = new ArrayList<>(); - try { - Activity activity = activityReference.get(); - if (activity != null) { - String json = ConvertUtils.toString(activity.getAssets().open("city.json")); - data.addAll(JSON.parseArray(json, Province.class)); - } - } catch (java.io.IOException e) { - e.printStackTrace(); - } - return data; - } - - @Override - protected void onPostExecute(ArrayList result) { - if (dialog != null) { - dialog.dismiss(); - } - if (result.size() > 0) { - Activity activity = activityReference.get(); - if (activity == null) { - return; - } - AddressPicker picker = new AddressPicker(activity, result); - picker.setHideProvince(hideProvince); - picker.setHideCounty(hideCounty); - if (hideCounty) { - picker.setColumnWeight(1 / 3.0f, 2 / 3.0f);//将屏幕分为3份,省级和地级的比例为1:2 - } else { - picker.setColumnWeight(2 / 8.0f, 3 / 8.0f, 3 / 8.0f);//省级、地级和县级的比例为2:3:3 - } - picker.setSelectedItem(selectedProvince, selectedCity, selectedCounty); - picker.setOnAddressPickListener(callback); - picker.show(); - } else { - callback.onAddressInitFailed(); - } - } - - public interface Callback extends AddressPicker.OnAddressPickListener { - - void onAddressInitFailed(); - - } - -} diff --git a/app/src/main/java/cn/qqtheme/androidpicker/AppManager.java b/app/src/main/java/cn/qqtheme/androidpicker/AppManager.java deleted file mode 100644 index 5ee0bef7..00000000 --- a/app/src/main/java/cn/qqtheme/androidpicker/AppManager.java +++ /dev/null @@ -1,126 +0,0 @@ -package cn.qqtheme.androidpicker; - -import android.app.Activity; -import android.app.Service; -import android.os.Bundle; - -import java.util.LinkedList; - -import cn.qqtheme.framework.util.LogUtils; - -/** - * Activity及Service管理,以便实现退出功能 - * - * @author 李玉江[QQ:1032694760] - * @since 2015/12/17 - */ -public class AppManager { - //本类的实例 - private static AppManager instance; - //保存所有Activity - private LinkedList activities = new LinkedList(); - //保存所有Service - private LinkedList services = new LinkedList(); - - public static AppManager getInstance() { - if (instance == null) { - instance = new AppManager(); - } - return instance; - } - - /** - * 注册Activity以便集中“finish()” - * - * @param activity the activity - * @see Activity#onCreate(Bundle) - * @see Activity#onStart() - */ - public void addActivity(Activity activity) { - activities.add(activity); - } - - /** - * 移除Activity. - * - * @param activity the activity - * @see Activity#onDestroy() - * @see Activity#onStop() - */ - public void removeActivity(Activity activity) { - activities.remove(activity); - } - - /** - * 所有的Activity - * - * @return the activities - */ - public LinkedList getActivities() { - return activities; - } - - /** - * 最后加入的Activity - * - * @return the activity - */ - public Activity getLastActivity() { - Activity activity = activities.getLast(); - LogUtils.debug(this, "last activity is " + activity.getClass().getName()); - return activity; - } - - /** - * 注册Service以便集中“stopSelf()” - * - * @param service the service - */ - public void addService(Service service) { - services.add(service); - } - - /** - * Remove service. - * - * @param service the service - */ - public void removeService(Service service) { - services.remove(service); - } - - /** - * 所有的Service - * - * @return the services - */ - public LinkedList getServices() { - return services; - } - - /** - * 退出软件 - */ - public void exitApp() { - clearActivitiesAndServices(); - android.os.Process.killProcess(android.os.Process.myPid()); - System.exit(0);//normal exit application - } - - /** - * 当内存不足时,需要清除已打开的Activity及Service - * - * @see android.app.Application#onLowMemory() - */ - public void clearActivitiesAndServices() { - for (Activity activity : activities) { - if (!activity.isFinishing()) { - activity.finish(); - } - } - for (Service service : services) { - service.stopSelf(); - } - } - -} diff --git a/app/src/main/java/cn/qqtheme/androidpicker/CustomHeaderAndFooterPicker.java b/app/src/main/java/cn/qqtheme/androidpicker/CustomHeaderAndFooterPicker.java deleted file mode 100644 index 10513cf7..00000000 --- a/app/src/main/java/cn/qqtheme/androidpicker/CustomHeaderAndFooterPicker.java +++ /dev/null @@ -1,140 +0,0 @@ -package cn.qqtheme.androidpicker; - -import android.animation.Animator; -import android.animation.AnimatorSet; -import android.animation.ObjectAnimator; -import android.app.Activity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.animation.AccelerateInterpolator; -import android.widget.Button; -import android.widget.TextView; - -import androidx.annotation.Nullable; -import cn.qqtheme.framework.picker.OptionPicker; -import cn.qqtheme.framework.widget.WheelView; - -/** - * 自定义顶部及底部 - *

- * Author:李玉江[QQ:1032694760] - * Email:liyujiang_tk@yeah.net - * DateTime:2016/1/29 14:47 - * Builder:Android Studio - */ -public class CustomHeaderAndFooterPicker extends OptionPicker implements OptionPicker.OnWheelListener { - private TextView titleView; - - public CustomHeaderAndFooterPicker(Activity activity) { - super(activity, new String[]{ - "Java/Android", "PHP/MySQL", "HTML/CSS/JS", "C/C++" - }); - setSelectedIndex(1); - setDividerRatio(WheelView.DividerConfig.FILL); - setOnWheelListener(this); - } - - @Override - protected void showAfter() { - View rootView = getRootView(); - AnimatorSet animatorSet = new AnimatorSet(); - ObjectAnimator alpha = ObjectAnimator.ofFloat(rootView, "alpha", 0, 1); - ObjectAnimator translation = ObjectAnimator.ofFloat(rootView, "translationY", 300, 0); - animatorSet.playTogether(alpha, translation); - animatorSet.setDuration(1000); - animatorSet.setInterpolator(new AccelerateInterpolator()); - animatorSet.start(); - } - - @Override - public void dismiss() { - View rootView = getRootView(); - AnimatorSet animatorSet = new AnimatorSet(); - ObjectAnimator alpha = ObjectAnimator.ofFloat(rootView, "alpha", 1, 0); - ObjectAnimator translation = ObjectAnimator.ofFloat(rootView, "translationX", 0, rootView.getWidth()); - ObjectAnimator rotation = ObjectAnimator.ofFloat(rootView, "rotation", 0, 120); - animatorSet.playTogether(alpha, translation, rotation); - animatorSet.setDuration(1000); - animatorSet.setInterpolator(new AccelerateInterpolator()); - animatorSet.addListener(new Animator.AnimatorListener() { - @Override - public void onAnimationStart(Animator animation) { - - } - - @Override - public void onAnimationEnd(Animator animation) { - dismissImmediately(); - } - - @Override - public void onAnimationCancel(Animator animation) { - - } - - @Override - public void onAnimationRepeat(Animator animation) { - - } - }); - animatorSet.start(); - } - - @Nullable - @Override - protected View makeHeaderView() { - View view = LayoutInflater.from(activity).inflate(R.layout.picker_header, null); - titleView = (TextView) view.findViewById(R.id.picker_title); - titleView.setText(titleText); - view.findViewById(R.id.picker_close).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - dismiss(); - } - }); - return view; - } - - @Nullable - @Override - protected View makeFooterView() { - View view = LayoutInflater.from(activity).inflate(R.layout.picker_footer, null); - Button submitView = (Button) view.findViewById(R.id.picker_submit); - submitView.setText(submitText); - submitView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - dismiss(); - onSubmit(); - } - }); - Button cancelView = (Button) view.findViewById(R.id.picker_cancel); - cancelView.setText(cancelText); - cancelView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - dismiss(); - onCancel(); - } - }); - return view; - } - - @Override - public void onWheeled(int index, String item) { - if (titleView != null) { - titleView.setText(item); - } - } - - @Override - public void onSubmit() { - super.onSubmit(); - } - - @Override - protected void onCancel() { - super.onCancel(); - } - -} diff --git a/app/src/main/java/cn/qqtheme/androidpicker/MainActivity.java b/app/src/main/java/cn/qqtheme/androidpicker/MainActivity.java deleted file mode 100644 index d5d89328..00000000 --- a/app/src/main/java/cn/qqtheme/androidpicker/MainActivity.java +++ /dev/null @@ -1,587 +0,0 @@ -package cn.qqtheme.androidpicker; - -import android.content.Intent; -import android.graphics.Color; -import android.net.Uri; -import android.view.Gravity; -import android.view.View; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import com.alibaba.fastjson.JSON; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.Locale; - -import cn.qqtheme.framework.entity.City; -import cn.qqtheme.framework.entity.County; -import cn.qqtheme.framework.entity.Province; -import cn.qqtheme.framework.picker.AddressPicker; -import cn.qqtheme.framework.picker.ColorPicker; -import cn.qqtheme.framework.picker.DatePicker; -import cn.qqtheme.framework.picker.DateTimePicker; -import cn.qqtheme.framework.picker.DoublePicker; -import cn.qqtheme.framework.picker.FilePicker; -import cn.qqtheme.framework.picker.LinkagePicker; -import cn.qqtheme.framework.picker.MultiplePicker; -import cn.qqtheme.framework.picker.NumberPicker; -import cn.qqtheme.framework.picker.OptionPicker; -import cn.qqtheme.framework.picker.SinglePicker; -import cn.qqtheme.framework.picker.TimePicker; -import cn.qqtheme.framework.util.ConvertUtils; -import cn.qqtheme.framework.util.DateUtils; -import cn.qqtheme.framework.util.LogUtils; -import cn.qqtheme.framework.util.StorageUtils; -import cn.qqtheme.framework.widget.WheelView; - -public class MainActivity extends BaseActivity { - - @Override - protected View getContentView() { - return inflateView(R.layout.activity_main); - } - - @Override - protected void setContentViewAfter(View contentView) { - - } - - @Override - public void onBackPressed() { - AppManager.getInstance().exitApp(); - } - - private void showToast(String msg) { - Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); - } - - public void onNestView(View view) { - startActivity(new Intent(this, NestActivity.class)); - } - - public void onAnimationStyle(View view) { - final NumberPicker picker = new NumberPicker(this); - picker.setItemWidth(200); - View headerView = View.inflate(activity, R.layout.picker_header, null); - final TextView titleView = (TextView) headerView.findViewById(R.id.picker_title); - titleView.setText("自定义顶部视图"); - headerView.findViewById(R.id.picker_close).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - picker.dismiss(); - } - }); - picker.setHeaderView(headerView); - picker.setAnimationStyle(R.style.Animation_CustomPopup); - picker.setCycleDisable(false); - picker.setOffset(5);//偏移量 - picker.setRange(10.5, 20, 1.5);//数字范围 - picker.setSelectedItem(18.0); - picker.setLabel("℃"); - picker.setOnWheelListener(new NumberPicker.OnWheelListener() { - @Override - public void onWheeled(int index, Number item) { - titleView.setText(String.valueOf(item.floatValue())); - } - }); - picker.show(); - } - - public void onAnimator(View view) { - CustomHeaderAndFooterPicker picker = new CustomHeaderAndFooterPicker(this); - picker.setOffset(3);//显示的条目的偏移量,条数为(offset*2+1) - picker.setGravity(Gravity.CENTER);//居中 - picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() { - @Override - public void onOptionPicked(int position, String option) { - showToast("index=" + position + ", item=" + option); - } - }); - picker.show(); - } - - public void onYearMonthDayPicker(View view) { - final DatePicker picker = new DatePicker(this); - picker.setCanceledOnTouchOutside(true); - picker.setUseWeight(true); - picker.setTopPadding(ConvertUtils.toPx(this, 10)); - picker.setRangeEnd(2111, 1, 11); - picker.setRangeStart(2016, 8, 29); - picker.setSelectedItem(2050, 10, 14); - picker.setResetWhileWheel(false); - picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() { - @Override - public void onDatePicked(String year, String month, String day) { - showToast(year + "-" + month + "-" + day); - } - }); - picker.setOnWheelListener(new DatePicker.OnWheelListener() { - @Override - public void onYearWheeled(int index, String year) { - picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay()); - } - - @Override - public void onMonthWheeled(int index, String month) { - picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay()); - } - - @Override - public void onDayWheeled(int index, String day) { - picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day); - } - }); - picker.show(); - } - - - public void onYearMonthDayTimePicker(View view) { - DateTimePicker picker = new DateTimePicker(this, DateTimePicker.HOUR_24); - picker.setDateRangeStart(2017, 1, 1); - picker.setDateRangeEnd(2025, 11, 11); - picker.setTimeRangeStart(9, 0); - picker.setTimeRangeEnd(20, 30); - picker.setTopLineColor(0x99FF0000); - picker.setLabelTextColor(0xFFFF0000); - picker.setDividerColor(0xFFFF0000); - picker.setOnDateTimePickListener(new DateTimePicker.OnYearMonthDayTimePickListener() { - @Override - public void onDateTimePicked(String year, String month, String day, String hour, String minute) { - showToast(year + "-" + month + "-" + day + " " + hour + ":" + minute); - } - }); - picker.show(); - } - - - public void onYearMonthPicker(View view) { - DatePicker picker = new DatePicker(this, DatePicker.YEAR_MONTH); - picker.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL); - picker.setWidth((int) (picker.getScreenWidthPixels() * 0.6)); - picker.setRangeStart(2016, 10, 14); - picker.setRangeEnd(2020, 11, 11); - picker.setSelectedItem(2017, 9); - picker.setOnDatePickListener(new DatePicker.OnYearMonthPickListener() { - @Override - public void onDatePicked(String year, String month) { - showToast(year + "-" + month); - } - }); - picker.show(); - } - - public void onMonthDayPicker(View view) { - DatePicker picker = new DatePicker(this, DatePicker.MONTH_DAY); - picker.setUseWeight(false); - picker.setTextPadding(ConvertUtils.toPx(this, 15));//加宽显示项 - picker.setGravity(Gravity.CENTER);//弹框居中 - picker.setRangeStart(5, 1); - picker.setRangeEnd(12, 31); - picker.setSelectedItem(10, 14); - picker.setOnDatePickListener(new DatePicker.OnMonthDayPickListener() { - @Override - public void onDatePicked(String month, String day) { - showToast(month + "-" + day); - } - }); - picker.show(); - } - - public void onTimePicker(View view) { - TimePicker picker = new TimePicker(this, TimePicker.HOUR_24); - picker.setUseWeight(false); - picker.setCycleDisable(false); - picker.setRangeStart(0, 0);//00:00 - picker.setRangeEnd(23, 59);//23:59 - int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); - int currentMinute = Calendar.getInstance().get(Calendar.MINUTE); - picker.setSelectedItem(currentHour, currentMinute); - picker.setTopLineVisible(false); - picker.setTextPadding(ConvertUtils.toPx(this, 15)); - picker.setOnTimePickListener(new TimePicker.OnTimePickListener() { - @Override - public void onTimePicked(String hour, String minute) { - showToast(hour + ":" + minute); - } - }); - picker.show(); - } - - public void onOptionPicker(View view) { - OptionPicker picker = new OptionPicker(this, new String[]{ - "第一项", "第二项", "第三项","第四项","第五项","第六项","第七项", - "这是一个很长很长很长很长很长很长很长很长很长的很长很长的很长很长的项" - }); - picker.setCanceledOnTouchOutside(false); - picker.setDividerRatio(WheelView.DividerConfig.FILL); - picker.setShadowColor(Color.RED, 40); - picker.setSelectedIndex(1); - picker.setCycleDisable(true); - picker.setTextSize(11); - picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() { - @Override - public void onOptionPicked(int index, String item) { - showToast("index=" + index + ", item=" + item); - } - }); - picker.show(); - } - - public void onSinglePicker(View view) { - List data = new ArrayList<>(); - data.add(new GoodsCategory(1, "食品生鲜")); - data.add(new GoodsCategory(2, "家用电器")); - data.add(new GoodsCategory(3, "家居生活")); - data.add(new GoodsCategory(4, "医疗保健")); - data.add(new GoodsCategory(5, "酒水饮料")); - data.add(new GoodsCategory(6, "图书音像")); - SinglePicker picker = new SinglePicker<>(this, data); - picker.setCanceledOnTouchOutside(false); - picker.setSelectedIndex(1); - picker.setCycleDisable(false); - picker.setOnItemPickListener(new SinglePicker.OnItemPickListener() { - @Override - public void onItemPicked(int index, GoodsCategory item) { - showToast("index=" + index + ", id=" + item.getId() + ", name=" + item.getName()); - } - }); - picker.show(); - } - - public void onDoublePicker(View view) { - final ArrayList firstData = new ArrayList<>(); - firstData.add("2017年5月2日星期二"); - firstData.add("2017年5月3日星期三"); - firstData.add("2017年5月4日星期四"); - firstData.add("2017年5月5日星期五"); - firstData.add("2017年5月6日星期六"); - final ArrayList secondData = new ArrayList<>(); - secondData.add("电动自行车"); - secondData.add("二轮摩托车"); - secondData.add("私家小汽车"); - secondData.add("公共交通汽车"); - final DoublePicker picker = new DoublePicker(this, firstData, secondData); - picker.setDividerVisible(true); - picker.setCycleDisable(false); - picker.setSelectedIndex(0, 0); - picker.setFirstLabel("于", null); - picker.setSecondLabel("骑/乘", "出发"); - picker.setTextSize(12); - picker.setContentPadding(15, 10); - picker.setOnPickListener(new DoublePicker.OnPickListener() { - @Override - public void onPicked(int selectedFirstIndex, int selectedSecondIndex) { - showToast(firstData.get(selectedFirstIndex) + " " + secondData.get(selectedSecondIndex)); - } - }); - picker.show(); - } - - public void onBusinessTimePicker(View view) { - final ArrayList hours = new ArrayList<>(); - for (int i = 0; i <= 23; i++) { - hours.add(DateUtils.fillZero(i)); - } - final ArrayList minutes = new ArrayList<>(); - minutes.add("00"); - minutes.add("15"); - minutes.add("30"); - DoublePicker picker = new DoublePicker(this, hours, minutes); - picker.setCanceledOnTouchOutside(true); - picker.setTopLineColor(0xFFFB2C3C); - picker.setSubmitTextColor(0xFFFB2C3C); - picker.setCancelTextColor(0xFFFB2C3C); - picker.setLineSpaceMultiplier(2.2f); - picker.setTextSize(15); - picker.setTitleText("营业时间"); - picker.setContentPadding(10, 8); - picker.setUseWeight(true); - picker.setFirstLabel("", ":"); - picker.setSecondLabel("", ""); - picker.setOnPickListener(new DoublePicker.OnPickListener() { - @Override - public void onPicked(int selectedFirstIndex, int selectedSecondIndex) { - showToast(hours.get(selectedFirstIndex) + ":" + minutes.get(selectedSecondIndex)); - } - }); - picker.show(); - } - - public void onMultiplePicker(View view) { - MultiplePicker picker = new MultiplePicker(this, new String[]{"穿青人", "少数民族", "已识别民族", "未定民族"}); - picker.setOnItemPickListener(new MultiplePicker.OnItemPickListener() { - @Override - public void onItemPicked(int count, List items) { - showToast("已选" + count + "项:" + items); - } - }); - picker.show(); - } - - public void onLinkagePicker(View view) { - //联动选择器的更多用法,可参见AddressPicker和CarNumberPicker - LinkagePicker.DataProvider provider = new LinkagePicker.DataProvider() { - - @Override - public boolean isOnlyTwo() { - return true; - } - - @NonNull - @Override - public List provideFirstData() { - ArrayList firstList = new ArrayList<>(); - firstList.add("12"); - firstList.add("24"); - return firstList; - } - - @NonNull - @Override - public List provideSecondData(int firstIndex) { - ArrayList secondList = new ArrayList<>(); - for (int i = 1; i <= (firstIndex == 0 ? 12 : 24); i++) { - String str = DateUtils.fillZero(i); - if (firstIndex == 0) { - str += "¥"; - } else { - str += "$"; - } - secondList.add(str); - } - return secondList; - } - - @Nullable - @Override - public List provideThirdData(int firstIndex, int secondIndex) { - return null; - } - - }; - LinkagePicker picker = new LinkagePicker(this, provider); - picker.setCycleDisable(true); - picker.setUseWeight(true); - picker.setLabel("小时制", "点"); - picker.setSelectedIndex(0, 8); - //picker.setSelectedItem("12", "9"); - picker.setContentPadding(10, 0); - picker.setOnStringPickListener(new LinkagePicker.OnStringPickListener() { - @Override - public void onPicked(String first, String second, String third) { - showToast(first + "-" + second + "-" + third); - } - }); - picker.show(); - } - - public void onConstellationPicker(View view) { - boolean isChinese = Locale.getDefault().getDisplayLanguage().contains("中文"); - OptionPicker picker = new OptionPicker(this, - isChinese ? new String[]{ - "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", - "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座" - } : new String[]{ - "Aquarius", "Pisces", "Aries", "Taurus", "Gemini", "Cancer", - "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn" - }); - picker.setCycleDisable(false);//不禁用循环 - picker.setTopBackgroundColor(0xFFEEEEEE); - picker.setTopHeight(30); - picker.setTopLineColor(0xFFEE0000); - picker.setTopLineHeight(1); - picker.setTitleText(isChinese ? "请选择" : "Please pick"); - picker.setTitleTextColor(0xFF999999); - picker.setTitleTextSize(12); - picker.setCancelTextColor(0xFFEE0000); - picker.setCancelTextSize(13); - picker.setSubmitTextColor(0xFFEE0000); - picker.setSubmitTextSize(13); - picker.setTextColor(0xFFEE0000, 0xFF999999); - WheelView.DividerConfig config = new WheelView.DividerConfig(); - config.setColor(0xFFEE0000);//线颜色 - config.setAlpha(140);//线透明度 - config.setRatio((float) (1.0 / 8.0));//线比率 - picker.setDividerConfig(config); - picker.setBackgroundColor(0xFFE1E1E1); - //picker.setSelectedItem(isChinese ? "处女座" : "Virgo"); - picker.setSelectedIndex(7); - picker.setCanceledOnTouchOutside(true); - picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() { - @Override - public void onOptionPicked(int index, String item) { - showToast("index=" + index + ", item=" + item); - } - }); - picker.show(); - } - - public void onNumberPicker(View view) { - NumberPicker picker = new NumberPicker(this); - picker.setWidth(picker.getScreenWidthPixels() / 2); - picker.setCycleDisable(false); - picker.setDividerVisible(false); - picker.setOffset(2);//偏移量 - picker.setRange(145, 200, 1);//数字范围 - picker.setSelectedItem(172); - picker.setLabel("厘米"); - picker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() { - @Override - public void onNumberPicked(int index, Number item) { - showToast("index=" + index + ", item=" + item.intValue()); - } - }); - picker.show(); - } - - public void onAddressPicker(View view) { - AddressPickTask task = new AddressPickTask(this); - task.setHideProvince(false); - task.setHideCounty(false); - task.setCallback(new AddressPickTask.Callback() { - @Override - public void onAddressInitFailed() { - showToast("数据初始化失败"); - } - - @Override - public void onAddressPicked(Province province, City city, County county) { - if (county == null) { - showToast(province.getAreaName() + city.getAreaName()); - } else { - showToast(province.getAreaName() + city.getAreaName() + county.getAreaName()); - } - } - }); - task.execute("贵州", "毕节", "纳雍"); - } - - public void onAddress2Picker(View view) { - try { - ArrayList data = new ArrayList<>(); - String json = ConvertUtils.toString(getAssets().open("city2.json")); - data.addAll(JSON.parseArray(json, Province.class)); - AddressPicker picker = new AddressPicker(this, data); - picker.setShadowVisible(true); - picker.setTextSizeAutoFit(false); - picker.setHideProvince(true); - picker.setSelectedItem("贵州", "贵阳", "花溪"); - picker.setOnAddressPickListener(new AddressPicker.OnAddressPickListener() { - @Override - public void onAddressPicked(Province province, City city, County county) { - showToast("province : " + province + ", city: " + city + ", county: " + county); - } - }); - picker.show(); - } catch (Exception e) { - showToast(LogUtils.toStackTraceString(e)); - } - } - - public void onAddress3Picker(View view) { - AddressPickTask task = new AddressPickTask(this); - task.setHideCounty(true); - task.setCallback(new AddressPickTask.Callback() { - @Override - public void onAddressInitFailed() { - showToast("数据初始化失败"); - } - - @Override - public void onAddressPicked(Province province, City city, County county) { - showToast(province.getAreaName() + " " + city.getAreaName()); - } - }); - task.execute("四川", "阿坝"); - } - - public void onAddress4Picker(View view) { - new AddressInitTask(this, new AddressInitTask.InitCallback() { - @Override - public void onDataInitFailure() { - showToast("数据初始化失败"); - } - - @Override - public void onDataInitSuccess(ArrayList provinces) { - AddressPicker picker = new AddressPicker(activity, provinces); - picker.setOnAddressPickListener(new AddressPicker.OnAddressPickListener() { - @Override - public void onAddressPicked(Province province, City city, County county) { - String provinceName = province.getName(); - String cityName = ""; - if (city != null) { - cityName = city.getName(); - //忽略直辖市的二级名称 - if (cityName.equals("市辖区") || cityName.equals("市") || cityName.equals("县")) { - cityName = ""; - } - } - String countyName = ""; - if (county != null) { - countyName = county.getName(); - } - showToast(provinceName + " " + cityName + " " + countyName); - } - }); - picker.show(); - } - }).execute(); - } - - public void onColorPicker(View view) { - ColorPicker picker = new ColorPicker(this); - picker.setInitColor(0xDD00DD); - picker.setOnColorPickListener(new ColorPicker.OnColorPickListener() { - @Override - public void onColorPicked(int pickedColor) { - showToast(ConvertUtils.toColorString(pickedColor)); - } - }); - picker.show(); - } - - public void onFilePicker(View view) { - FilePicker picker = new FilePicker(this, FilePicker.FILE); - picker.setShowHideDir(false); - //picker.setAllowExtensions(new String[]{".apk"}); - picker.setFileIcon(getResources().getDrawable(android.R.drawable.ic_menu_agenda)); - picker.setFolderIcon(getResources().getDrawable(android.R.drawable.ic_menu_upload_you_tube)); - //picker.setArrowIcon(getResources().getDrawable(android.R.drawable.arrow_down_float)); - picker.setOnFilePickListener(new FilePicker.OnFilePickListener() { - @Override - public void onFilePicked(String currentPath) { - showToast(currentPath); - } - }); - picker.show(); - } - - public void onDirPicker(View view) { - FilePicker picker = new FilePicker(this, FilePicker.DIRECTORY); - picker.setRootPath(StorageUtils.getExternalRootPath() + "Download/"); - picker.setItemHeight(30); - picker.setOnFilePickListener(new FilePicker.OnFilePickListener() { - @Override - public void onFilePicked(String currentPath) { - showToast(currentPath); - } - }); - picker.show(); - } - - public void onContact(View view) { - Intent intent = new Intent(Intent.ACTION_SENDTO); - intent.setData(Uri.parse("mailto:liyujiang_tk@yeah.net")); - intent.putExtra(Intent.EXTRA_CC, new String[] - {"1032694760@qq.com"}); - intent.putExtra(Intent.EXTRA_EMAIL, ""); - intent.putExtra(Intent.EXTRA_TEXT, "欢迎提供意您的见或建议"); - startActivity(Intent.createChooser(intent, "选择邮件客户端")); - } - -} diff --git a/app/src/main/java/cn/qqtheme/androidpicker/MyPickerApp.java b/app/src/main/java/cn/qqtheme/androidpicker/MyPickerApp.java deleted file mode 100644 index 72c2069e..00000000 --- a/app/src/main/java/cn/qqtheme/androidpicker/MyPickerApp.java +++ /dev/null @@ -1,25 +0,0 @@ -package cn.qqtheme.androidpicker; - -import android.app.Application; - -import cn.qqtheme.framework.AppConfig; -import cn.qqtheme.framework.util.LogUtils; - -/** - * Author:李玉江[QQ:1032694760] - * DateTime:2016/7/20 20:28 - * Builder:Android Studio - */ -public class MyPickerApp extends Application { - - @Override - public void onCreate() { - super.onCreate(); - if (BuildConfig.DEBUG) { - LogUtils.setIsDebug(true); - } else { - android.util.Log.d(AppConfig.DEBUG_TAG, "LogCat is disabled"); - } - } - -} diff --git a/app/src/main/java/cn/qqtheme/androidpicker/NestActivity.java b/app/src/main/java/cn/qqtheme/androidpicker/NestActivity.java deleted file mode 100644 index 062126db..00000000 --- a/app/src/main/java/cn/qqtheme/androidpicker/NestActivity.java +++ /dev/null @@ -1,92 +0,0 @@ -package cn.qqtheme.androidpicker; - -import android.view.View; -import android.widget.LinearLayout; -import android.widget.TextView; - -import java.util.Locale; - -import cn.qqtheme.framework.picker.CarNumberPicker; -import cn.qqtheme.framework.picker.DatePicker; -import cn.qqtheme.framework.picker.DateTimePicker; -import cn.qqtheme.framework.util.ConvertUtils; -import cn.qqtheme.framework.widget.WheelView; - -/** - * 内嵌选择器 - *
- * Author:李玉江[QQ:1032694760] - * DateTime:2016/12/16 00:42 - * Builder:Android Studio - */ -public class NestActivity extends BaseActivity { - - @Override - protected View getContentView() { - return inflateView(R.layout.activity_nest); - } - - @Override - protected void setContentViewAfter(View contentView) { - findViewById(R.id.nest_back).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); - - final TextView textView = findView(R.id.wheelview_tips); - WheelView wheelView = findView(R.id.wheelview_single); - final String[] strings = {"少数民族", "贵州穿青人", "不在56个少数民族之列", "第57个民族"}; - wheelView.setItems(strings, 2); - wheelView.setTextColor(0xFFFF00FF); - wheelView.setTextSize(18); - WheelView.DividerConfig config = new WheelView.DividerConfig(); - config.setRatio(1.0f / 10.0f);//线比率 - config.setColor(0xFFFF0000);//线颜色 - config.setAlpha(100);//线透明度 - config.setThick(ConvertUtils.toPx(this, 5));//线粗 - wheelView.setDividerConfig(config); - wheelView.setOnItemSelectListener(new WheelView.OnItemSelectListener() { - @Override - public void onSelected(int index) { - textView.setText(String.format(Locale.PRC, "index=%d,item=%s", index, strings[index])); - } - }); - - LinearLayout layout = findView(R.id.wheelview_container); - final CarNumberPicker carNumberPicker = new CarNumberPicker(this); - carNumberPicker.setOffset(3); - carNumberPicker.setUseWeight(true); - carNumberPicker.setShadowColor(0xFFCCCCCC); - carNumberPicker.setDividerRatio(WheelView.DividerConfig.FILL); - carNumberPicker.setOnWheelLinkageListener(new CarNumberPicker.OnWheelLinkageListener() { - @Override - public void onLinkage(int firstIndex, int secondIndex, int thirdIndex) { - textView.setText(String.format(Locale.PRC, "%s:%s", carNumberPicker.getSelectedFirstItem(), carNumberPicker.getSelectedSecondItem())); - } - }); - layout.addView(carNumberPicker.getContentView()); - final DatePicker datePicker = new DatePicker(this, DateTimePicker.YEAR_MONTH_DAY); - datePicker.setOffset(4); - datePicker.setOnWheelListener(new DatePicker.OnWheelListener() { - @Override - public void onYearWheeled(int index, String year) { - textView.setText(String.format("%s年%s月%s日", year, datePicker.getSelectedMonth(), datePicker.getSelectedDay())); - } - - @Override - public void onMonthWheeled(int index, String month) { - textView.setText(String.format("%s年%s月%s日", datePicker.getSelectedYear(), month, datePicker.getSelectedDay())); - } - - @Override - public void onDayWheeled(int index, String day) { - textView.setText(String.format("%s年%s月%s日", datePicker.getSelectedYear(), datePicker.getSelectedMonth(), day)); - } - }); - //得到选择器视图,可内嵌到其他视图容器,不需要调用show方法 - layout.addView(datePicker.getContentView()); - } - -} diff --git a/app/src/main/java/cn/qqtheme/androidpicker/StatusBarUtil.java b/app/src/main/java/cn/qqtheme/androidpicker/StatusBarUtil.java deleted file mode 100644 index 44c1f230..00000000 --- a/app/src/main/java/cn/qqtheme/androidpicker/StatusBarUtil.java +++ /dev/null @@ -1,542 +0,0 @@ -package cn.qqtheme.androidpicker; - -import android.annotation.SuppressLint; -import android.annotation.TargetApi; -import android.app.Activity; -import android.content.Context; -import android.graphics.Color; -import android.os.Build; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import android.view.WindowManager; -import android.widget.LinearLayout; - -import java.lang.reflect.Field; - -import androidx.annotation.ColorInt; -import androidx.annotation.IdRes; -import androidx.drawerlayout.widget.DrawerLayout; -import cn.qqtheme.framework.util.LogUtils; - -/** - * 状态栏(通知栏)工具类 - *

- * Created by liyujiang on 2017/4/19 15:35. - */ -public class StatusBarUtil { - private static final int DEFAULT_ALPHA = 0; - @SuppressLint("ResourceType") - @IdRes - private static final int FAKE_STATUS_BAR_VIEW_ID = 0x20170419; - @SuppressLint("ResourceType") - @IdRes - private static final int FAKE_TRANSLUCENT_VIEW_ID = 0x20170420; - private static final int TAG_KEY_HAVE_SET_OFFSET = -123; - private static int height = 0; - - /** - * 是否设置了沉浸状态栏 - */ - public static boolean isImmersion(Activity activity) { - return activity.findViewById(FAKE_STATUS_BAR_VIEW_ID) != null - || activity.findViewById(FAKE_TRANSLUCENT_VIEW_ID) != null; - } - - /** - * 设置状态栏颜色 - * - * @param activity 需要设置的 activity - * @param color 状态栏颜色值 - */ - public static void setColor(Activity activity, @ColorInt int color) { - setColor(activity, color, DEFAULT_ALPHA); - } - - /** - * 设置状态栏颜色 - * - * @param activity 需要设置的activity - * @param color 状态栏颜色值 - * @param statusBarAlpha 状态栏透明度 - */ - - public static void setColor(Activity activity, @ColorInt int color, int statusBarAlpha) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - activity.getWindow().setStatusBarColor(calculateStatusColor(color, statusBarAlpha)); - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); - View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); - if (fakeStatusBarView != null) { - if (fakeStatusBarView.getVisibility() == View.GONE) { - fakeStatusBarView.setVisibility(View.VISIBLE); - } - fakeStatusBarView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); - } else { - decorView.addView(createStatusBarView(activity, color, statusBarAlpha)); - } - setRootView(activity); - } - } - - /** - * 设置状态栏纯色 不加半透明效果 - * - * @param activity 需要设置的 activity - * @param color 状态栏颜色值 - */ - public static void setColorNoTranslucent(Activity activity, @ColorInt int color) { - setColor(activity, color, 0); - } - - /** - * 使状态栏半透明 - *

- * 适用于图片作为背景的界面,此时需要图片填充到状态栏 - * - * @param activity 需要设置的activity - */ - public static void setTranslucent(Activity activity) { - setTranslucent(activity, DEFAULT_ALPHA); - } - - /** - * 使状态栏半透明 - *

- * 适用于图片作为背景的界面,此时需要图片填充到状态栏 - * - * @param activity 需要设置的activity - * @param statusBarAlpha 状态栏透明度 - */ - public static void setTranslucent(Activity activity, int statusBarAlpha) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { - return; - } - setTransparent(activity); - addTranslucentView(activity, statusBarAlpha); - } - - /** - * 针对根布局是 CoordinatorLayout, 使状态栏半透明 - *

- * 适用于图片作为背景的界面,此时需要图片填充到状态栏 - * - * @param activity 需要设置的activity - * @param statusBarAlpha 状态栏透明度 - */ - public static void setTranslucentForCoordinatorLayout(Activity activity, int statusBarAlpha) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { - return; - } - setTransparentForWindow(activity); - addTranslucentView(activity, statusBarAlpha); - } - - /** - * 设置状态栏全透明 - * - * @param activity 需要设置的activity - */ - public static void setTransparent(Activity activity) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { - return; - } - setTransparentForWindow(activity); - setRootView(activity); - } - - /** - * 为DrawerLayout 布局设置状态栏变色 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - * @param color 状态栏颜色值 - */ - public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { - setColorForDrawerLayout(activity, drawerLayout, color, DEFAULT_ALPHA); - } - - /** - * 为DrawerLayout 布局设置状态栏颜色,纯色 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - * @param color 状态栏颜色值 - */ - public static void setColorNoTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { - setColorForDrawerLayout(activity, drawerLayout, color, 0); - } - - /** - * 为DrawerLayout 布局设置状态栏变色 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - * @param color 状态栏颜色值 - * @param statusBarAlpha 状态栏透明度 - */ - public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color, - int statusBarAlpha) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { - return; - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - activity.getWindow().setStatusBarColor(Color.TRANSPARENT); - } else { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - } - // 生成一个状态栏大小的矩形 - // 添加 statusBarView 到布局中 - ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); - View fakeStatusBarView = contentLayout.findViewById(FAKE_STATUS_BAR_VIEW_ID); - if (fakeStatusBarView != null) { - if (fakeStatusBarView.getVisibility() == View.GONE) { - fakeStatusBarView.setVisibility(View.VISIBLE); - } - fakeStatusBarView.setBackgroundColor(color); - } else { - contentLayout.addView(createStatusBarView(activity, color), 0); - } - // 内容布局不是 LinearLayout 时,设置padding top - if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { - contentLayout.getChildAt(1) - .setPadding(contentLayout.getPaddingLeft(), obtainHeight(activity) + contentLayout.getPaddingTop(), - contentLayout.getPaddingRight(), contentLayout.getPaddingBottom()); - } - // 设置属性 - setDrawerLayoutProperty(drawerLayout, contentLayout); - addTranslucentView(activity, statusBarAlpha); - } - - /** - * 设置 DrawerLayout 属性 - * - * @param drawerLayout DrawerLayout - * @param drawerLayoutContentLayout DrawerLayout 的内容布局 - */ - private static void setDrawerLayoutProperty(DrawerLayout drawerLayout, ViewGroup drawerLayoutContentLayout) { - ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); - drawerLayout.setFitsSystemWindows(false); - drawerLayoutContentLayout.setFitsSystemWindows(false); - drawerLayoutContentLayout.setClipToPadding(true); - drawer.setFitsSystemWindows(false); - } - - /** - * 为 DrawerLayout 布局设置状态栏透明 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - */ - public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) { - setTranslucentForDrawerLayout(activity, drawerLayout, DEFAULT_ALPHA); - } - - /** - * 为 DrawerLayout 布局设置状态栏透明 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - */ - public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, int statusBarAlpha) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { - return; - } - setTransparentForDrawerLayout(activity, drawerLayout); - addTranslucentView(activity, statusBarAlpha); - } - - /** - * 为 DrawerLayout 布局设置状态栏透明 - * - * @param activity 需要设置的activity - * @param drawerLayout DrawerLayout - */ - public static void setTransparentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { - return; - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - activity.getWindow().setStatusBarColor(Color.TRANSPARENT); - } else { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - } - - ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); - // 内容布局不是 LinearLayout 时,设置padding top - if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { - contentLayout.getChildAt(1).setPadding(0, obtainHeight(activity), 0, 0); - } - - // 设置属性 - setDrawerLayoutProperty(drawerLayout, contentLayout); - } - - /** - * 为头部是 ImageView 的界面设置状态栏全透明 - * - * @param activity 需要设置的activity - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTransparentForImageView(Activity activity, View needOffsetView) { - setTranslucentForImageView(activity, 0, needOffsetView); - } - - /** - * 为头部是 ImageView 的界面设置状态栏透明(使用默认透明度) - * - * @param activity 需要设置的activity - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTranslucentForImageView(Activity activity, View needOffsetView) { - setTranslucentForImageView(activity, DEFAULT_ALPHA, needOffsetView); - } - - /** - * 为头部是 ImageView 的界面设置状态栏透明 - * - * @param activity 需要设置的activity - * @param statusBarAlpha 状态栏透明度 - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTranslucentForImageView(Activity activity, int statusBarAlpha, View needOffsetView) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { - return; - } - setTransparentForWindow(activity); - addTranslucentView(activity, statusBarAlpha); - if (needOffsetView != null) { - Object haveSetOffset = needOffsetView.getTag(TAG_KEY_HAVE_SET_OFFSET); - if (haveSetOffset != null && (Boolean) haveSetOffset) { - return; - } - ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) needOffsetView.getLayoutParams(); - layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin + obtainHeight(activity), - layoutParams.rightMargin, layoutParams.bottomMargin); - needOffsetView.setTag(TAG_KEY_HAVE_SET_OFFSET, true); - } - } - - /** - * 为 fragment 头部是 ImageView 的设置状态栏透明 - * - * @param activity fragment 对应的 activity - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTranslucentForImageViewInFragment(Activity activity, View needOffsetView) { - setTranslucentForImageViewInFragment(activity, DEFAULT_ALPHA, needOffsetView); - } - - /** - * 为 fragment 头部是 ImageView 的设置状态栏透明 - * - * @param activity fragment 对应的 activity - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTransparentForImageViewInFragment(Activity activity, View needOffsetView) { - setTranslucentForImageViewInFragment(activity, 0, needOffsetView); - } - - /** - * 为 fragment 头部是 ImageView 的设置状态栏透明 - * - * @param activity fragment 对应的 activity - * @param statusBarAlpha 状态栏透明度 - * @param needOffsetView 需要向下偏移的 View - */ - public static void setTranslucentForImageViewInFragment(Activity activity, int statusBarAlpha, View needOffsetView) { - setTranslucentForImageView(activity, statusBarAlpha, needOffsetView); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { - clearPreviousSetting(activity); - } - } - - /** - * 隐藏伪状态栏 View - * - * @param activity 调用的 Activity - */ - public static void hideFakeStatusBarView(Activity activity) { - ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); - View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); - if (fakeStatusBarView != null) { - fakeStatusBarView.setVisibility(View.GONE); - } - View fakeTranslucentView = decorView.findViewById(FAKE_TRANSLUCENT_VIEW_ID); - if (fakeTranslucentView != null) { - fakeTranslucentView.setVisibility(View.GONE); - } - } - - /////////////////////////////////////////////////////////////////////////////////// - - @TargetApi(Build.VERSION_CODES.KITKAT) - private static void clearPreviousSetting(Activity activity) { - ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); - View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); - if (fakeStatusBarView != null) { - decorView.removeView(fakeStatusBarView); - ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); - rootView.setPadding(0, 0, 0, 0); - } - } - - /** - * 添加半透明矩形条 - * - * @param activity 需要设置的 activity - * @param statusBarAlpha 透明值 - */ - private static void addTranslucentView(Activity activity, int statusBarAlpha) { - ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); - View fakeTranslucentView = contentView.findViewById(FAKE_TRANSLUCENT_VIEW_ID); - if (fakeTranslucentView != null) { - if (fakeTranslucentView.getVisibility() == View.GONE) { - fakeTranslucentView.setVisibility(View.VISIBLE); - } - fakeTranslucentView.setBackgroundColor(Color.argb(statusBarAlpha, 0, 0, 0)); - } else { - contentView.addView(createTranslucentStatusBarView(activity, statusBarAlpha)); - } - } - - /** - * 生成一个和状态栏大小相同的彩色矩形条 - * - * @param activity 需要设置的 activity - * @param color 状态栏颜色值 - * @return 状态栏矩形条 - */ - private static View createStatusBarView(Activity activity, @ColorInt int color) { - return createStatusBarView(activity, color, 0); - } - - /** - * 生成一个和状态栏大小相同的半透明矩形条 - * - * @param activity 需要设置的activity - * @param color 状态栏颜色值 - * @param alpha 透明值 - * @return 状态栏矩形条 - */ - private static View createStatusBarView(Activity activity, @ColorInt int color, int alpha) { - // 绘制一个和状态栏一样高的矩形 - View statusBarView = new View(activity); - LinearLayout.LayoutParams params = - new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, obtainHeight(activity)); - statusBarView.setLayoutParams(params); - statusBarView.setBackgroundColor(calculateStatusColor(color, alpha)); - statusBarView.setId(FAKE_STATUS_BAR_VIEW_ID); - return statusBarView; - } - - /** - * 设置根布局参数 - */ - private static void setRootView(Activity activity) { - ViewGroup parent = (ViewGroup) activity.findViewById(android.R.id.content); - for (int i = 0, count = parent.getChildCount(); i < count; i++) { - View childView = parent.getChildAt(i); - if (childView instanceof ViewGroup) { - childView.setFitsSystemWindows(true); - ((ViewGroup) childView).setClipToPadding(true); - } - } - } - - /** - * 设置透明 - */ - private static void setTransparentForWindow(Activity activity) { - Window window = activity.getWindow(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - window.setStatusBarColor(Color.TRANSPARENT); - window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - } - } - - /** - * 创建半透明矩形 View - * - * @param alpha 透明值 - * @return 半透明 View - */ - private static View createTranslucentStatusBarView(Activity activity, int alpha) { - // 绘制一个和状态栏一样高的矩形 - View statusBarView = new View(activity); - LinearLayout.LayoutParams params = - new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, obtainHeight(activity)); - statusBarView.setLayoutParams(params); - statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0)); - statusBarView.setId(FAKE_TRANSLUCENT_VIEW_ID); - return statusBarView; - } - - /** - * 获取状态栏的高,单位为px,参阅:http://blog.csdn.net/a_running_wolf/article/details/50477965 - */ - public static int obtainHeight(Context context) { - if (height != 0) { - return height; - } - int result = 80;// px - try { - int dimenResId = obtainDimenResId(context); - result = context.getResources().getDimensionPixelSize(dimenResId); - } catch (Exception e) { - LogUtils.warn(e); - if (context instanceof Activity) { - android.graphics.Rect frame = new android.graphics.Rect(); - ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); - result = frame.top; - } - } - LogUtils.verbose("status bar height: " + result + " px"); - height = result; - return result; - } - - private static int obtainDimenResId(Context ctx) throws ClassNotFoundException, - NoSuchFieldException, IllegalAccessException, InstantiationException { - LogUtils.verbose("will obtain status bar height from dimen resources"); - int resourceId = ctx.getResources().getIdentifier("status_bar_height", "dimen", "android"); - if (resourceId > 0) { - return resourceId; - } - LogUtils.verbose("will obtain status bar height from R$dimen class"); - Class clazz = Class.forName("com.android.internal.R$dimen"); - Field field = clazz.getField("status_bar_height"); - Object object = field.get(clazz.newInstance()); - return Integer.parseInt(object.toString()); - } - - /** - * 计算状态栏颜色 - * - * @param color color值 - * @param alpha alpha值 - * @return 最终的状态栏颜色 - */ - private static int calculateStatusColor(@ColorInt int color, int alpha) { - if (alpha == 0) { - return color; - } - float a = 1 - alpha / 255f; - int red = color >> 16 & 0xff; - int green = color >> 8 & 0xff; - int blue = color & 0xff; - red = (int) (red * a + 0.5); - green = (int) (green * a + 0.5); - blue = (int) (blue * a + 0.5); - return 0xff << 24 | red << 16 | green << 8 | blue; - } -} diff --git a/app/src/main/res/layout/activity_nest.xml b/app/src/main/res/layout/activity_nest.xml deleted file mode 100644 index 2fb08bcc..00000000 --- a/app/src/main/res/layout/activity_nest.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/layout/picker_footer.xml b/app/src/main/res/layout/picker_footer.xml deleted file mode 100644 index d9fd2b80..00000000 --- a/app/src/main/res/layout/picker_footer.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - -