commit 8bf98c660ac0ac90d002f9d592bf419b848f8d5e Author: linglongxin24 Date: Mon May 23 16:26:42 2016 +0800 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c6cbe56 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..bb17c9a --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +AndroidFrame \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..96cc43e --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..e7bedf3 --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..97626ba --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..86756a2 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,25 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..1a3eaff --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..8965c05 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..7f68460 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..adc000c --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,26 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 23 + buildToolsVersion "23.0.3" + + defaultConfig { + applicationId "com.kejiang.yuandl.sample" + minSdkVersion 15 + targetSdkVersion 22 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(include: ['*.jar'], dir: 'libs') + testCompile 'junit:junit:4.12' + compile project(':libray_lxndroid') +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..d28a1a5 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\kejiang\Android\sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/app/src/androidTest/java/com/kejiang/yuandl/ApplicationTest.java b/app/src/androidTest/java/com/kejiang/yuandl/ApplicationTest.java new file mode 100644 index 0000000..a689204 --- /dev/null +++ b/app/src/androidTest/java/com/kejiang/yuandl/ApplicationTest.java @@ -0,0 +1,13 @@ +package com.kejiang.yuandl; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cf8f746 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/kejiang/yuandl/sample/MainActivity.java b/app/src/main/java/com/kejiang/yuandl/sample/MainActivity.java new file mode 100644 index 0000000..de1e838 --- /dev/null +++ b/app/src/main/java/com/kejiang/yuandl/sample/MainActivity.java @@ -0,0 +1,31 @@ +package com.kejiang.yuandl.sample; + +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; + +import com.kejiang.yuandl.base.BaseActivity; + +public class MainActivity extends BaseActivity { + + @Override + public void initTitleBar() { + setTitle("试试"); + + } + + @Override + public void initViews() { + + setContentView(R.layout.activity_main); + } + + @Override + public void initData() { + + } + + @Override + public void addListener() { + + } +} diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..b23061b --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,16 @@ + + + + + diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..cde69bc Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..c133a0c Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..bfa42f0 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..324e72c Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..aee44e1 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/values-w820dp/dimens.xml b/app/src/main/res/values-w820dp/dimens.xml new file mode 100644 index 0000000..63fc816 --- /dev/null +++ b/app/src/main/res/values-w820dp/dimens.xml @@ -0,0 +1,6 @@ + + + 64dp + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..3ab3e9c --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #3F51B5 + #303F9F + #FF4081 + diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml new file mode 100644 index 0000000..47c8224 --- /dev/null +++ b/app/src/main/res/values/dimens.xml @@ -0,0 +1,5 @@ + + + 16dp + 16dp + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..d47251e --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + AndroidFrame + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..5885930 --- /dev/null +++ b/app/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/app/src/test/java/com/kejiang/yuandl/ExampleUnitTest.java b/app/src/test/java/com/kejiang/yuandl/ExampleUnitTest.java new file mode 100644 index 0000000..601f284 --- /dev/null +++ b/app/src/test/java/com/kejiang/yuandl/ExampleUnitTest.java @@ -0,0 +1,15 @@ +package com.kejiang.yuandl; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * To work on unit tests, switch the Test Artifact in the Build Variants view. + */ +public class ExampleUnitTest { + @Test + public void addition_isCorrect() throws Exception { + assertEquals(4, 2 + 2); + } +} \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..03bced9 --- /dev/null +++ b/build.gradle @@ -0,0 +1,23 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..1d3591c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..13372ae Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..122a0dc --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Dec 28 10:00:20 PST 2015 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..9d82f78 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..8a0b282 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/libray_lxndroid/.gitignore b/libray_lxndroid/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/libray_lxndroid/.gitignore @@ -0,0 +1 @@ +/build diff --git a/libray_lxndroid/build.gradle b/libray_lxndroid/build.gradle new file mode 100644 index 0000000..7c0cc8c --- /dev/null +++ b/libray_lxndroid/build.gradle @@ -0,0 +1,36 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion 23 + buildToolsVersion "23.0.3" + + defaultConfig { + minSdkVersion 15 + targetSdkVersion 22 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(include: ['*.jar'], dir: 'libs') + testCompile 'junit:junit:4.12' + compile 'com.android.support:appcompat-v7:23.3.0' + compile 'com.zhy:autolayout:1.4.3' + compile 'com.orhanobut:logger:1.8' + compile 'org.xutils:xutils:3.3.34' + compile 'com.android.support:recyclerview-v7:23.3.0' + compile 'com.linglongxin24:UncaughtExceptionSendEmail:1.0.0' + + debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1' + // or 1.4-beta1 + releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1' + // or 1.4-beta1 + testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1' +} diff --git a/libray_lxndroid/libs/fastjson-1.1.43.android.jar b/libray_lxndroid/libs/fastjson-1.1.43.android.jar new file mode 100644 index 0000000..483fd1e Binary files /dev/null and b/libray_lxndroid/libs/fastjson-1.1.43.android.jar differ diff --git a/libray_lxndroid/proguard-rules.pro b/libray_lxndroid/proguard-rules.pro new file mode 100644 index 0000000..d28a1a5 --- /dev/null +++ b/libray_lxndroid/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\kejiang\Android\sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/libray_lxndroid/src/androidTest/java/com/kejiang/yuandl/ApplicationTest.java b/libray_lxndroid/src/androidTest/java/com/kejiang/yuandl/ApplicationTest.java new file mode 100644 index 0000000..a689204 --- /dev/null +++ b/libray_lxndroid/src/androidTest/java/com/kejiang/yuandl/ApplicationTest.java @@ -0,0 +1,13 @@ +package com.kejiang.yuandl; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/AndroidManifest.xml b/libray_lxndroid/src/main/AndroidManifest.xml new file mode 100644 index 0000000..bb1c358 --- /dev/null +++ b/libray_lxndroid/src/main/AndroidManifest.xml @@ -0,0 +1,12 @@ + + + + + + + diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/FragmentTabAdapter.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/FragmentTabAdapter.java new file mode 100644 index 0000000..38af7aa --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/FragmentTabAdapter.java @@ -0,0 +1,133 @@ +package com.kykj.inspection.adapter; + +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentActivity; +import android.support.v4.app.FragmentTransaction; +import android.widget.RadioGroup; +import android.widget.RadioGroup.OnCheckedChangeListener; + +import java.util.List; + +/** + * fragment切换适配器 + */ +public class FragmentTabAdapter implements OnCheckedChangeListener { + + private List fragments; // 一个tab页面对应一个Fragment + private RadioGroup rg; // 用于切换tab + private FragmentActivity fragmentActivity; // Fragment所属的Activity + private int fragmentContentId; // Activity中所要被替换的区域的id + + private int currentTab =0;// 当前Tab页面索引 + + private OnRgsExtraCheckedChangedListener onRgsExtraCheckedChangedListener; // 用于让调用者在切换tab时候增加新的功能 + + public FragmentTabAdapter(FragmentActivity fragmentActivity, List fragments, int fragmentContentId, RadioGroup rg) { + this.fragments = fragments; + this.rg = rg; + this.fragmentActivity = fragmentActivity; + this.fragmentContentId = fragmentContentId; + + // 默认显示第一页 + FragmentTransaction ft = fragmentActivity.getSupportFragmentManager() + .beginTransaction(); + ft.add(fragmentContentId, fragments.get(currentTab)); + ft.commit(); + if(rg!=null){ + rg.setOnCheckedChangeListener(this); + } + + + } + + @Override + public void onCheckedChanged(RadioGroup radioGroup, int checkedId) { + for (int i = 0; i < rg.getChildCount(); i++) { + if (rg.getChildAt(i).getId() == checkedId) { + Fragment fragment = fragments.get(i); + FragmentTransaction ft = obtainFragmentTransaction(i); + // getCurrentFragment().onPause(); // 暂停当前tab + //getCurrentFragment().onStop(); // 暂停当前tab + + if (fragment.isAdded()) { + // fragment.onStart(); // 启动目标tab的onStart() + currentTab=i; + fragment.onResume(); // 启动目标tab的onResume() + } else { + ft.add(fragmentContentId, fragment); + } + showTab(i); // 显示目标tab + ft.commit(); + + // 如果设置了切换tab额外功能功能接口 + if (null != onRgsExtraCheckedChangedListener) { + onRgsExtraCheckedChangedListener.OnRgsExtraCheckedChanged( + radioGroup, checkedId, i); + } + + } + } + + } + + /** + * 切换tab + * + * @param idx + */ + public void showTab(int idx) { + for (int i = 0; i < fragments.size(); i++) { + Fragment fragment = fragments.get(i); + FragmentTransaction ft = obtainFragmentTransaction(idx); + + if (idx == i) { + ft.show(fragment); + } else { + ft.hide(fragment); + } + ft.commit(); + } + currentTab = idx; // 更新目标tab为当前tab + } + + /** + * 获取一个带动画的FragmentTransaction + * + * @param index + * @return + */ + private FragmentTransaction obtainFragmentTransaction(int index) { + FragmentTransaction ft = fragmentActivity.getSupportFragmentManager() + .beginTransaction(); + + return ft; + } + + public int getCurrentTab() { + return currentTab; + } + + public Fragment getCurrentFragment() { + return fragments.get(currentTab); + } + + public OnRgsExtraCheckedChangedListener getOnRgsExtraCheckedChangedListener() { + return onRgsExtraCheckedChangedListener; + } + + public void setOnRgsExtraCheckedChangedListener( + OnRgsExtraCheckedChangedListener onRgsExtraCheckedChangedListener) { + this.onRgsExtraCheckedChangedListener = onRgsExtraCheckedChangedListener; + } + + /** + * 切换tab额外功能功能接口 + */ + public static class OnRgsExtraCheckedChangedListener { + public void OnRgsExtraCheckedChanged(RadioGroup radioGroup, + int checkedId, int index) { + + } + } + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/ViewHolder.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/ViewHolder.java new file mode 100644 index 0000000..6339b61 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/ViewHolder.java @@ -0,0 +1,251 @@ +package com.kejiang.yuandl.adapter.common; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Paint; +import android.graphics.Typeface; +import android.graphics.drawable.Drawable; +import android.os.Build; +import android.support.v7.widget.RecyclerView; +import android.text.util.Linkify; +import android.util.SparseArray; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.animation.AlphaAnimation; +import android.widget.Checkable; +import android.widget.ImageView; +import android.widget.ProgressBar; +import android.widget.RatingBar; +import android.widget.TextView; + +public class ViewHolder extends RecyclerView.ViewHolder { + private SparseArray mViews; + private int mPosition; + private View mConvertView; + private Context mContext; + private int mLayoutId; + + public int getMyPosition() { + return mPosition; + } + + public ViewHolder(Context context, View itemView, ViewGroup parent, int position) { + super(itemView); + mContext = context; + mConvertView = itemView; + mPosition = position; + mViews = new SparseArray(); + mConvertView.setTag(this); + + } + + + public static ViewHolder get(Context context, View convertView, + ViewGroup parent, int layoutId, int position) { + if (convertView == null) { + View itemView = LayoutInflater.from(context).inflate(layoutId, parent, + false); + ViewHolder holder = new ViewHolder(context, itemView, parent, position); + holder.mLayoutId = layoutId; + return holder; + } else { + ViewHolder holder = (ViewHolder) convertView.getTag(); + holder.mPosition = position; + return holder; + } + } + + + /** + * 通过viewId获取控件 + * + * @param viewId + * @return + */ + public T getView(int viewId) { + View view = mViews.get(viewId); + if (view == null) { + view = mConvertView.findViewById(viewId); + mViews.put(viewId, view); + } + return (T) view; + } + + public View getConvertView() { + return mConvertView; + } + + /** + * 设置TextView的值 + * + * @param viewId + * @param text + * @return + */ + public ViewHolder setText(int viewId, String text) { + TextView tv = getView(viewId); + tv.setText(text); + return this; + } + + public ViewHolder setImageResource(int viewId, int resId) { + ImageView view = getView(viewId); + view.setImageResource(resId); + return this; + } + + public ViewHolder setImageBitmap(int viewId, Bitmap bitmap) { + ImageView view = getView(viewId); + view.setImageBitmap(bitmap); + return this; + } + + public ViewHolder setImageDrawable(int viewId, Drawable drawable) { + ImageView view = getView(viewId); + view.setImageDrawable(drawable); + return this; + } + + public ViewHolder setBackgroundColor(int viewId, int color) { + View view = getView(viewId); + view.setBackgroundColor(color); + return this; + } + + public ViewHolder setBackgroundRes(int viewId, int backgroundRes) { + View view = getView(viewId); + view.setBackgroundResource(backgroundRes); + return this; + } + + public ViewHolder setTextColor(int viewId, int textColor) { + TextView view = getView(viewId); + view.setTextColor(textColor); + return this; + } + + public ViewHolder setTextColorRes(int viewId, int textColorRes) { + TextView view = getView(viewId); + view.setTextColor(mContext.getResources().getColor(textColorRes)); + return this; + } + + @SuppressLint("NewApi") + public ViewHolder setAlpha(int viewId, float value) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + getView(viewId).setAlpha(value); + } else { + // Pre-honeycomb hack to set Alpha value + AlphaAnimation alpha = new AlphaAnimation(value, value); + alpha.setDuration(0); + alpha.setFillAfter(true); + getView(viewId).startAnimation(alpha); + } + return this; + } + + public ViewHolder setVisible(int viewId, boolean visible) { + View view = getView(viewId); + view.setVisibility(visible ? View.VISIBLE : View.GONE); + return this; + } + + public ViewHolder linkify(int viewId) { + TextView view = getView(viewId); + Linkify.addLinks(view, Linkify.ALL); + return this; + } + + public ViewHolder setTypeface(Typeface typeface, int... viewIds) { + for (int viewId : viewIds) { + TextView view = getView(viewId); + view.setTypeface(typeface); + view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG); + } + return this; + } + + public ViewHolder setProgress(int viewId, int progress) { + ProgressBar view = getView(viewId); + view.setProgress(progress); + return this; + } + + public ViewHolder setProgress(int viewId, int progress, int max) { + ProgressBar view = getView(viewId); + view.setMax(max); + view.setProgress(progress); + return this; + } + + public ViewHolder setMax(int viewId, int max) { + ProgressBar view = getView(viewId); + view.setMax(max); + return this; + } + + public ViewHolder setRating(int viewId, float rating) { + RatingBar view = getView(viewId); + view.setRating(rating); + return this; + } + + public ViewHolder setRating(int viewId, float rating, int max) { + RatingBar view = getView(viewId); + view.setMax(max); + view.setRating(rating); + return this; + } + + public ViewHolder setTag(int viewId, Object tag) { + View view = getView(viewId); + view.setTag(tag); + return this; + } + + public ViewHolder setTag(int viewId, int key, Object tag) { + View view = getView(viewId); + view.setTag(key, tag); + return this; + } + + public ViewHolder setChecked(int viewId, boolean checked) { + Checkable view = (Checkable) getView(viewId); + view.setChecked(checked); + return this; + } + + /** + * 关于事件的 + */ + public ViewHolder setOnClickListener(int viewId, + View.OnClickListener listener) { + View view = getView(viewId); + view.setOnClickListener(listener); + return this; + } + + public ViewHolder setOnTouchListener(int viewId, + View.OnTouchListener listener) { + View view = getView(viewId); + view.setOnTouchListener(listener); + return this; + } + + public ViewHolder setOnLongClickListener(int viewId, + View.OnLongClickListener listener) { + View view = getView(viewId); + view.setOnLongClickListener(listener); + return this; + } + + public void updatePosition(int position) { + mPosition = position; + } + + public int getLayoutId() { + return mLayoutId; + } +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/abslistview/CommonAdapter.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/abslistview/CommonAdapter.java new file mode 100644 index 0000000..de861fd --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/abslistview/CommonAdapter.java @@ -0,0 +1,58 @@ +package com.kejiang.yuandl.adapter.common.abslistview; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; + + +import com.kejiang.yuandl.adapter.common.ViewHolder; + +import java.util.List; + +public abstract class CommonAdapter extends BaseAdapter +{ + protected Context mContext; + protected List mDatas; + protected LayoutInflater mInflater; + private int layoutId; + + public CommonAdapter(Context context,int layoutId, List datas ) + { + this.mContext = context; + mInflater = LayoutInflater.from(context); + this.mDatas = datas; + this.layoutId = layoutId; + } + + @Override + public int getCount() + { + return mDatas.size(); + } + + @Override + public T getItem(int position) + { + return mDatas.get(position); + } + + @Override + public long getItemId(int position) + { + return position; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) + { + ViewHolder holder = ViewHolder.get(mContext, convertView, parent, + layoutId, position); + convert(holder, getItem(position)); + return holder.getConvertView(); + } + + public abstract void convert(ViewHolder holder, T t); + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/abslistview/MultiItemCommonAdapter.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/abslistview/MultiItemCommonAdapter.java new file mode 100644 index 0000000..3519803 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/abslistview/MultiItemCommonAdapter.java @@ -0,0 +1,58 @@ +package com.kejiang.yuandl.adapter.common.abslistview; + +import android.content.Context; +import android.view.View; +import android.view.ViewGroup; + + +import com.kejiang.yuandl.adapter.common.ViewHolder; + +import java.util.List; + +public abstract class MultiItemCommonAdapter extends CommonAdapter +{ + + protected MultiItemTypeSupport mMultiItemTypeSupport; + + public MultiItemCommonAdapter(Context context, List datas, + MultiItemTypeSupport multiItemTypeSupport) + { + super(context, -1, datas); + mMultiItemTypeSupport = multiItemTypeSupport; + if (mMultiItemTypeSupport == null) + throw new IllegalArgumentException("the mMultiItemTypeSupport can not be null."); + } + + @Override + public int getViewTypeCount() + { + if (mMultiItemTypeSupport != null) + return mMultiItemTypeSupport.getViewTypeCount(); + return super.getViewTypeCount(); + } + + @Override + public int getItemViewType(int position) + { + if (mMultiItemTypeSupport != null) + return mMultiItemTypeSupport.getItemViewType(position, + mDatas.get(position)); + return super.getItemViewType(position); + + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) + { + if (mMultiItemTypeSupport == null) + return super.getView(position, convertView, parent); + + int layoutId = mMultiItemTypeSupport.getLayoutId(position, + getItem(position)); + ViewHolder viewHolder = ViewHolder.get(mContext, convertView, parent, + layoutId, position); + convert(viewHolder, getItem(position)); + return viewHolder.getConvertView(); + } + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/abslistview/MultiItemTypeSupport.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/abslistview/MultiItemTypeSupport.java new file mode 100644 index 0000000..ce905a2 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/abslistview/MultiItemTypeSupport.java @@ -0,0 +1,10 @@ +package com.kejiang.yuandl.adapter.common.abslistview; + +public interface MultiItemTypeSupport +{ + int getLayoutId(int position, T t); + + int getViewTypeCount(); + + int getItemViewType(int position, T t); +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/CommonAdapter.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/CommonAdapter.java new file mode 100644 index 0000000..dada422 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/CommonAdapter.java @@ -0,0 +1,106 @@ +package com.kejiang.yuandl.adapter.common.recyclerview; + +import android.content.Context; +import android.support.v7.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + + +import com.kejiang.yuandl.adapter.common.ViewHolder; + +import java.util.List; + +/** + * Created by zhy on 16/4/9. + */ +public abstract class CommonAdapter extends RecyclerView.Adapter +{ + protected Context mContext; + protected int mLayoutId; + protected List mDatas; + protected LayoutInflater mInflater; + + private OnItemClickListener mOnItemClickListener; + + public void setOnItemClickListener(OnItemClickListener onItemClickListener) + { + this.mOnItemClickListener = onItemClickListener; + } + + public CommonAdapter(Context context, int layoutId, List datas) + { + mContext = context; + mInflater = LayoutInflater.from(context); + mLayoutId = layoutId; + mDatas = datas; + } + + @Override + public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) + { + ViewHolder viewHolder = ViewHolder.get(mContext, null, parent, mLayoutId, -1); + setListener(parent, viewHolder, viewType); + return viewHolder; + } + + protected int getPosition(RecyclerView.ViewHolder viewHolder) + { + return viewHolder.getAdapterPosition(); + } + + protected boolean isEnabled(int viewType) + { + return true; + } + + + protected void setListener(final ViewGroup parent, final ViewHolder viewHolder, int viewType) + { + if (!isEnabled(viewType)) return; + viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() + { + @Override + public void onClick(View v) + { + if (mOnItemClickListener != null) + { + int position = getPosition(viewHolder); + mOnItemClickListener.onItemClick(parent, v, mDatas.get(position), position); + } + } + }); + + + viewHolder.getConvertView().setOnLongClickListener(new View.OnLongClickListener() + { + @Override + public boolean onLongClick(View v) + { + if (mOnItemClickListener != null) + { + int position = getPosition(viewHolder); + return mOnItemClickListener.onItemLongClick(parent, v, mDatas.get(position), position); + } + return false; + } + }); + } + + @Override + public void onBindViewHolder(ViewHolder holder, int position) + { + holder.updatePosition(position); + convert(holder, mDatas.get(position)); + } + + public abstract void convert(ViewHolder holder, T t); + + @Override + public int getItemCount() + { + return mDatas.size(); + } + + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/DividerItemDecoration.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/DividerItemDecoration.java new file mode 100644 index 0000000..b94a989 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/DividerItemDecoration.java @@ -0,0 +1,104 @@ +package com.kejiang.yuandl.adapter.common.recyclerview;/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * limitations under the License. + */ + +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.view.View; + + +/** + * This class is from the v7 samples of the Android SDK. It's not by me! + *

+ * See the license above for details. + */ +public class DividerItemDecoration extends RecyclerView.ItemDecoration { + + private static final int[] ATTRS = new int[]{ + android.R.attr.listDivider + }; + + public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; + + public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; + + private Drawable mDivider; + + private int mOrientation; + + public DividerItemDecoration(Context context, int orientation) { + final TypedArray a = context.obtainStyledAttributes(ATTRS); + mDivider = a.getDrawable(0); + a.recycle(); + setOrientation(orientation); + } + + public void setOrientation(int orientation) { + if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { + throw new IllegalArgumentException("invalid orientation"); + } + mOrientation = orientation; + } + + @Override + public void onDraw(Canvas c, RecyclerView parent) { + + if (mOrientation == VERTICAL_LIST) { + drawVertical(c, parent); + } else { + drawHorizontal(c, parent); + } + + } + + + public void drawVertical(Canvas c, RecyclerView parent) { + final int left = parent.getPaddingLeft(); + final int right = parent.getWidth() - parent.getPaddingRight(); + + final int childCount = parent.getChildCount(); + for (int i = 0; i < childCount; i++) { + final View child = parent.getChildAt(i); + android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext()); + final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child + .getLayoutParams(); + final int top = child.getBottom() + params.bottomMargin; + final int bottom = top + mDivider.getIntrinsicHeight(); + mDivider.setBounds(left, top, right, bottom); + mDivider.draw(c); + } + } + + public void drawHorizontal(Canvas c, RecyclerView parent) { + final int top = parent.getPaddingTop(); + final int bottom = parent.getHeight() - parent.getPaddingBottom(); + + final int childCount = parent.getChildCount(); + for (int i = 0; i < childCount; i++) { + final View child = parent.getChildAt(i); + final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child + .getLayoutParams(); + final int left = child.getRight() + params.rightMargin; + final int right = left + mDivider.getIntrinsicHeight(); + mDivider.setBounds(left, top, right, bottom); + mDivider.draw(c); + } + } + + @Override + public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { + if (mOrientation == VERTICAL_LIST) { + outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); + } else { + outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); + } + } +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/EmptyRecyclerView.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/EmptyRecyclerView.java new file mode 100644 index 0000000..96cb117 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/EmptyRecyclerView.java @@ -0,0 +1,85 @@ +package com.kejiang.yuandl.adapter.common.recyclerview; + +import android.content.Context; +import android.support.v7.widget.RecyclerView; +import android.util.AttributeSet; +import android.view.View; + +/** + * https://gist.github.com/adelnizamutdinov/31c8f054d1af4588dc5c + */ +public class EmptyRecyclerView extends RecyclerView +{ + View emptyView; + + public EmptyRecyclerView(Context context) + { + super(context); + } + + public EmptyRecyclerView(Context context, AttributeSet attrs) + { + super(context, attrs); + } + + public EmptyRecyclerView(Context context, AttributeSet attrs, int defStyle) + { + super(context, attrs, defStyle); + } + + void checkIfEmpty() + { + if (emptyView != null) + { + emptyView.setVisibility(getAdapter().getItemCount() > 0 ? GONE : VISIBLE); + } + } + + final AdapterDataObserver observer = new AdapterDataObserver() + { + @Override + public void onChanged() + { + super.onChanged(); + checkIfEmpty(); + } + }; + + @Override + public void swapAdapter(Adapter adapter, boolean removeAndRecycleExistingViews) + { + final Adapter oldAdapter = getAdapter(); + if (oldAdapter != null) + { + oldAdapter.unregisterAdapterDataObserver(observer); + } + + if (adapter != null) + { + adapter.registerAdapterDataObserver(observer); + } + super.swapAdapter(adapter, removeAndRecycleExistingViews); + checkIfEmpty(); + } + + @Override + public void setAdapter(Adapter adapter) + { + final Adapter oldAdapter = getAdapter(); + if (oldAdapter != null) + { + oldAdapter.unregisterAdapterDataObserver(observer); + } + super.setAdapter(adapter); + if (adapter != null) + { + adapter.registerAdapterDataObserver(observer); + } + } + + public void setEmptyView(View emptyView) + { + this.emptyView = emptyView; + checkIfEmpty(); + } +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/MultiItemCommonAdapter.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/MultiItemCommonAdapter.java new file mode 100644 index 0000000..b3f1b04 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/MultiItemCommonAdapter.java @@ -0,0 +1,45 @@ +package com.kejiang.yuandl.adapter.common.recyclerview; + +import android.content.Context; +import android.view.ViewGroup; + + +import com.kejiang.yuandl.adapter.common.ViewHolder; + +import java.util.List; + +public abstract class MultiItemCommonAdapter extends CommonAdapter +{ + + protected MultiItemTypeSupport mMultiItemTypeSupport; + + public MultiItemCommonAdapter(Context context, List datas, + MultiItemTypeSupport multiItemTypeSupport) + { + super(context, -1, datas); + mMultiItemTypeSupport = multiItemTypeSupport; + + if (mMultiItemTypeSupport == null) + throw new IllegalArgumentException("the mMultiItemTypeSupport can not be null."); + } + + @Override + public int getItemViewType(int position) + { + if (mMultiItemTypeSupport != null) + return mMultiItemTypeSupport.getItemViewType(position, mDatas.get(position)); + return super.getItemViewType(position); + } + + @Override + public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) + { + if (mMultiItemTypeSupport == null) return super.onCreateViewHolder(parent, viewType); + + int layoutId = mMultiItemTypeSupport.getLayoutId(viewType); + ViewHolder holder = ViewHolder.get(mContext, null, parent, layoutId, -1); + setListener(parent, holder, viewType); + return holder; + } + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/MultiItemTypeSupport.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/MultiItemTypeSupport.java new file mode 100644 index 0000000..d7d8ee8 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/MultiItemTypeSupport.java @@ -0,0 +1,8 @@ +package com.kejiang.yuandl.adapter.common.recyclerview; + +public interface MultiItemTypeSupport +{ + int getLayoutId(int itemType); + + int getItemViewType(int position, T t); +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/OnItemClickListener.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/OnItemClickListener.java new file mode 100644 index 0000000..27ca91a --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/OnItemClickListener.java @@ -0,0 +1,10 @@ +package com.kejiang.yuandl.adapter.common.recyclerview; + +import android.view.View; +import android.view.ViewGroup; + +public interface OnItemClickListener +{ + void onItemClick(ViewGroup parent, View view, T t, int position); + boolean onItemLongClick(ViewGroup parent, View view, T t, int position); +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/support/SectionAdapter.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/support/SectionAdapter.java new file mode 100644 index 0000000..062a9f2 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/support/SectionAdapter.java @@ -0,0 +1,192 @@ +package com.kejiang.yuandl.adapter.common.recyclerview.support; + +import android.content.Context; +import android.support.v7.widget.RecyclerView; + +import com.kejiang.yuandl.adapter.common.ViewHolder; +import com.kejiang.yuandl.adapter.common.recyclerview.MultiItemCommonAdapter; +import com.kejiang.yuandl.adapter.common.recyclerview.MultiItemTypeSupport; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Created by zhy on 16/4/9. + */ +public abstract class SectionAdapter extends MultiItemCommonAdapter +{ + private SectionSupport mSectionSupport; + private static final int TYPE_SECTION = 0; + private LinkedHashMap mSections; + + private MultiItemTypeSupport headerItemTypeSupport; + + @Override + public int getItemViewType(int position) + { + return mMultiItemTypeSupport.getItemViewType(position, null); + } + + final RecyclerView.AdapterDataObserver observer = new RecyclerView.AdapterDataObserver() + { + @Override + public void onChanged() + { + super.onChanged(); + findSections(); + } + }; + + public SectionAdapter(Context context, int layoutId, List datas, SectionSupport sectionSupport) + { + this(context, layoutId, null, datas, sectionSupport); + } + + public SectionAdapter(Context context, MultiItemTypeSupport multiItemTypeSupport, List datas, SectionSupport sectionSupport) + { + this(context, -1, multiItemTypeSupport, datas, sectionSupport); + } + + public SectionAdapter(Context context, int layoutId, MultiItemTypeSupport multiItemTypeSupport, List datas, SectionSupport sectionSupport) + { + super(context, datas, null); + mLayoutId = layoutId; + initMulitiItemTypeSupport(layoutId, multiItemTypeSupport); + mMultiItemTypeSupport = headerItemTypeSupport; + mSectionSupport = sectionSupport; + mSections = new LinkedHashMap(); + findSections(); + registerAdapterDataObserver(observer); + } + + private void initMulitiItemTypeSupport(int layoutId, final MultiItemTypeSupport multiItemTypeSupport) + { + if (layoutId != -1) + { + headerItemTypeSupport = new MultiItemTypeSupport() + { + @Override + public int getLayoutId(int itemType) + { + if (itemType == TYPE_SECTION) + return mSectionSupport.sectionHeaderLayoutId(); + else + return mLayoutId; + } + + @Override + public int getItemViewType(int position, T o) + { + int positionVal = getIndexForPosition(position); + return mSections.values().contains(position) ? + TYPE_SECTION : + 1; + } + }; + } else if (multiItemTypeSupport != null) + { + headerItemTypeSupport = new MultiItemTypeSupport() + { + @Override + public int getLayoutId(int itemType) + { + if (itemType == TYPE_SECTION) + return mSectionSupport.sectionHeaderLayoutId(); + else + return multiItemTypeSupport.getLayoutId(itemType); + } + + @Override + public int getItemViewType(int position, T o) + { + int positionVal = getIndexForPosition(position); + return mSections.values().contains(position) ? + TYPE_SECTION : + multiItemTypeSupport.getItemViewType(positionVal, o); + } + }; + } else + { + throw new RuntimeException("layoutId or MultiItemTypeSupport must set one."); + } + + } + + @Override + protected boolean isEnabled(int viewType) + { + if (viewType == TYPE_SECTION) + return false; + return super.isEnabled(viewType); + } + + @Override + public void onDetachedFromRecyclerView(RecyclerView recyclerView) + { + super.onDetachedFromRecyclerView(recyclerView); + unregisterAdapterDataObserver(observer); + } + + public void findSections() + { + int n = mDatas.size(); + int nSections = 0; + mSections.clear(); + + for (int i = 0; i < n; i++) + { + String sectionName = mSectionSupport.getTitle(mDatas.get(i)); + + if (!mSections.containsKey(sectionName)) + { + mSections.put(sectionName, i + nSections); + nSections++; + } + } + + } + + + @Override + public int getItemCount() + { + return super.getItemCount() + mSections.size(); + } + + public int getIndexForPosition(int position) + { + int nSections = 0; + + Set> entrySet = mSections.entrySet(); + for (Map.Entry entry : entrySet) + { + if (entry.getValue() < position) + { + nSections++; + } + } + return position - nSections; + } + + @Override + protected int getPosition(RecyclerView.ViewHolder viewHolder) + { + return getIndexForPosition(viewHolder.getAdapterPosition()); + } + + @Override + public void onBindViewHolder(ViewHolder holder, int position) + { + position = getIndexForPosition(position); + if (holder.getItemViewType() == TYPE_SECTION) + { + holder.setText(mSectionSupport.sectionTitleTextViewId(), mSectionSupport.getTitle(mDatas.get(position))); + return; + } + super.onBindViewHolder(holder, position); + } + + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/support/SectionSupport.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/support/SectionSupport.java new file mode 100644 index 0000000..217b90b --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/adapter/common/recyclerview/support/SectionSupport.java @@ -0,0 +1,13 @@ +package com.kejiang.yuandl.adapter.common.recyclerview.support; + +/** + * Created by zhy on 16/4/9. + */ +public interface SectionSupport +{ + public int sectionHeaderLayoutId(); + + public int sectionTitleTextViewId(); + + public String getTitle(T t); +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/app/MyApplication.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/app/MyApplication.java new file mode 100644 index 0000000..813b748 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/app/MyApplication.java @@ -0,0 +1,49 @@ +package com.kejiang.yuandl.app; + +import android.app.Application; +import android.app.admin.SystemUpdatePolicy; +import android.content.Context; +import android.os.Vibrator; + +import com.squareup.leakcanary.LeakCanary; +import com.kejiang.yuandl.mylibrary.CustomActivityOnCrash; +import com.orhanobut.logger.Logger; +import com.squareup.leakcanary.RefWatcher; + +import org.xutils.x; + +/** + * Created by yuandl on 2016/5/23 0023. + */ +public class MyApplication extends Application { + + private RefWatcher refWatcher; + + @Override + public void onCreate() { + super.onCreate(); + CustomActivityOnCrash.install(this); + CustomActivityOnCrash.setDebugMode(true); + String[] emialTo = {"yuandl@Bluemobi.cn", "kangfh@Bluemobi.cn"}; + CustomActivityOnCrash.setEmailTo(emialTo); + Logger.init("law"); + x.Ext.init(this); +// refWatcher = LeakCanary.install(this); + refWatcher = installLeakCanary(); + } + + @Override + public void onLowMemory() { + super.onLowMemory(); + System.gc(); + } + + public static RefWatcher getRefWatcher(Context context) { + MyApplication application = (MyApplication) context.getApplicationContext(); + return application.refWatcher; + } + + protected RefWatcher installLeakCanary() { + return RefWatcher.DISABLED; + } +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/base/BaseActivity.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/base/BaseActivity.java new file mode 100644 index 0000000..5bcc879 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/base/BaseActivity.java @@ -0,0 +1,632 @@ +package com.kejiang.yuandl.base; + +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.graphics.drawable.Drawable; +import android.os.Build; +import android.os.Bundle; +import android.support.v4.util.ArrayMap; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.TypeReference; +import com.kejiang.yuandl.R; +import com.kejiang.yuandl.bean.JsonBean; +import com.kejiang.yuandl.utils.AppManager; +import com.kejiang.yuandl.utils.CheckNetwork; +import com.kejiang.yuandl.utils.Tools; +import com.kejiang.yuandl.view.LoadingDialog; +import com.orhanobut.logger.Logger; +import com.zhy.autolayout.AutoLayoutActivity; +import com.zhy.autolayout.utils.AutoUtils; + +import org.xutils.common.Callback; +import org.xutils.common.util.KeyValue; +import org.xutils.common.util.MD5; +import org.xutils.ex.HttpException; +import org.xutils.http.RequestParams; +import org.xutils.x; + +import java.util.List; +import java.util.Map; + +/** + * com.bm.falvzixun.activities.BaseActivity; + * + * @author yuandl on 2015/12/17. + * 所有页面的基类 + */ +public abstract class BaseActivity extends AutoLayoutActivity implements View.OnClickListener { + private TextView mTitleTextView; + private ImageView mBackwardbButton; + private TextView mForwardButton; + private FrameLayout mContentLayout; + private LinearLayout llRoot; + private LinearLayout layout_titlebar; + protected Context context; + Dialog dialog; + /** + * 加载数据对话框 + */ + public LoadingDialog loadingDialog; + private Callback.Cancelable cancelable; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + AppManager.getAppManager().addActivity(this); + setImmersionStatus(); + setupViews(); + context = this; + initTitleBar(); + initViews(); + initData(); + addListener(); + } + + public TextView getmForwardButton() { + return mForwardButton; + } + + public ImageView getmBackwardbButton() { + return mBackwardbButton; + } + + /** + * 初始化设置标题栏 + */ + public abstract void initTitleBar(); + + /** + * 初始化view控件 + */ + public abstract void initViews(); + + /** + * 初始化数据 + */ + public abstract void initData(); + + /** + * 给view添加事件监听 + */ + public abstract void addListener(); + + /** + * 设置沉浸式状态栏 + */ + private void setImmersionStatus() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + // 透明状态栏 + getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + // 透明导航栏 + getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); + } + } + + /** + * 加载 activity_title 布局 ,并获取标题及两侧按钮 + */ + private void setupViews() { + super.setContentView(R.layout.ac_title); + llRoot = (LinearLayout) findViewById(R.id.llRoot); + AutoUtils.auto(llRoot); + layout_titlebar = (LinearLayout) findViewById(R.id.layout_titlebar); + mTitleTextView = (TextView) findViewById(R.id.text_title); + mContentLayout = (FrameLayout) findViewById(R.id.layout_content); + mBackwardbButton = (ImageView) findViewById(R.id.button_backward); + mForwardButton = (TextView) findViewById(R.id.button_forward); + } + + /** + * 设置标题栏是否可见 + * + * @param visibility + */ + public void setTitleBarVisible(int visibility) { + layout_titlebar.setVisibility(visibility); + } + + /** + * 设置标题栏的整体背景颜色(含沉浸式状态栏) + * + * @param color + */ + public void setTitleBarBackground(int color) { + setStatusBarBackground(color); + layout_titlebar.setBackgroundColor(color); + } + + /** + * 设置返回按钮背景图片(含沉浸式状态栏) + * + * @param drawable + */ + public void setBackwardButtonBackgroundDrawable(Drawable drawable, LinearLayout.LayoutParams layoutParams) { + mBackwardbButton.setImageDrawable(drawable); + mBackwardbButton.setLayoutParams(layoutParams); + AutoUtils.auto(mBackwardbButton); + } + + /** + * 设置返回按钮背景图片(含沉浸式状态栏) + * + * @param drawable + */ + public void setBackwardButtonBackgroundDrawable(Drawable drawable) { + mBackwardbButton.setImageDrawable(drawable); + } + + /** + * 设置浸式状态栏的整体背景颜色 + * + * @param color + */ + public void setStatusBarBackground(int color) { + llRoot.setBackgroundColor(color); + } + + /** + * 设置浸式状态栏的整体背景图片(慎用) + * + * @param drawable + */ + public void setStatusBarBackgroundDrawable(Drawable drawable) { + llRoot.setBackgroundDrawable(drawable); + } + + /** + * 是否显示返回按钮 + * + * @param backwardResid 文字 + * @param show true则显示 + */ + protected void showBackwardView(int backwardResid, boolean show) { + if (mBackwardbButton != null) { + if (show) { +// mBackwardbButton.setText(backwardResid); + mBackwardbButton.setVisibility(View.VISIBLE); + } else { + mBackwardbButton.setVisibility(View.INVISIBLE); + } + } // else ignored + } + + protected void setBackwardViewLayoutParams(LinearLayout.LayoutParams layoutParams) { + if (mBackwardbButton != null) { + mBackwardbButton.setLayoutParams(layoutParams); + } + } + + protected void setForwardViewLayoutParams(LinearLayout.LayoutParams layoutParams) { + if (mForwardButton != null) { + mForwardButton.setLayoutParams(layoutParams); + } + } + + /** + * 提供是否显示提交按钮 + * + * @param forwardResId 文字 + * @param show true则显示 + */ + protected void showForwardView(int forwardResId, boolean show) { + if (mForwardButton != null) { + if (show) { + mForwardButton.setVisibility(View.VISIBLE); + mForwardButton.setText(forwardResId); + } else { + mForwardButton.setVisibility(View.INVISIBLE); + } + } // else ignored + } + + /** + * 提供是否显示提交按钮 + * + * @param title 文字 + * @param show true则显示 + */ + protected void showForwardView(CharSequence title, boolean show) { + if (mForwardButton != null) { + if (show) { + mForwardButton.setText(title); + mForwardButton.setVisibility(View.VISIBLE); + + } else { + mForwardButton.setVisibility(View.INVISIBLE); + } + } // else ignored + } + + /** + * 返回按钮点击后触发 + * + * @param backwardView + */ + public void onBackward(View backwardView) { +// Toast.makeText(this, "点击返回,可在此处调用finish()", Toast.LENGTH_LONG).show(); + finish(); + } + + /** + * 提交按钮点击后触发 + * + * @param forwardView + */ + public void onForward(View forwardView) { + Toast.makeText(this, "点击提交", Toast.LENGTH_LONG).show(); + } + + //设置标题内容 + @Override + public void setTitle(int titleId) { + mTitleTextView.setText(titleId); + } + + //设置标题内容 + @Override + public void setTitle(CharSequence title) { + mTitleTextView.setText(title); + } + + //设置标题文字颜色 + @Override + public void setTitleColor(int textColor) { + mTitleTextView.setTextColor(textColor); + } + + + //取出FrameLayout并调用父类removeAllViews()方法 + @Override + public void setContentView(int layoutResID) { + mContentLayout.removeAllViews(); + View.inflate(this, layoutResID, mContentLayout); + onContentChanged(); + } + + @Override + public void setContentView(View view) { + mContentLayout.removeAllViews(); + mContentLayout.addView(view); + onContentChanged(); + } + + /* (non-Javadoc) + * @see android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams) + */ + @Override + public void setContentView(View view, ViewGroup.LayoutParams params) { + mContentLayout.removeAllViews(); + mContentLayout.addView(view, params); + onContentChanged(); + } + + private Toast toast; + + /** + * 弹出Toast便捷方法 + * + * @param charSequence + */ + public void showToast(CharSequence charSequence) { + if (null == toast) { + toast = Toast.makeText(x.app(), charSequence, Toast.LENGTH_SHORT); + } else { + toast.setText(charSequence); + } + toast.show(); + + } + + @Override + protected void onPause() { + super.onPause(); + if (null != toast) { + toast.cancel(); + } + + } + + /* (non-Javadoc) + * @see android.view.View.OnClickListener#onClick(android.view.View) + * 按钮点击调用的方法 + */ + @Override + public void onClick(View v) { +// +// switch (v.getId()) { +// case R.id.button_backward: +// onBackward(v); +// break; +// +// case R.id.button_forward: +// onForward(v); +// break; +// +// default: +// break; +// } + } + + /** + * activity跳转 + * + * @param c + */ + protected void startActivity(Class c) { + startActivity(new Intent(context, c)); + } + + /** + * 异步网络请求类 + * + * @param requestParams + */ + protected void ajax(RequestParams requestParams) { + if (!CheckNetwork.isNetworkAvailable(context)) { + showToast("网络不可用,请检查网络连接!"); + return; + } + if (loadingDialog == null) { + loadingDialog = new LoadingDialog(context); + } + if (requestParams != null) { + String uri = requestParams.getUri(); + if (!uri.isEmpty()) { + String[] split = uri.split("/"); +// Logger.d("split=" + Arrays.toString(split)); + + String method = null; + try { + method = split[split.length - 1].substring(0, split[split.length - 1].indexOf(".")); + } catch (Exception e) { + e.printStackTrace(); + Logger.d("请检查服务器地址后面是否含有.html"); + } + String mode = split[split.length - 2]; + String sign = MD5.md5(mode + method); + requestParams.addBodyParameter("sign", sign); + } + + } + Logger.d("url=" + requestParams.getUri() + "\nrequestParams=" + requestParams.getStringParams().toString()); + List params = requestParams.getStringParams(); + for (KeyValue keyValue : params) { + if (keyValue.key.contains(":")) { + throw new RuntimeException("参数异常!"); + } + } + // jsonBean = JSON.parseObject(result, JsonBean.class); + cancelable = x.http().post(requestParams, new Callback.ProgressCallback() { + + @Override + public void onWaiting() { + } + + @Override + + public void onStarted() { + netOnStart(); + } + + @Override + public void onLoading(long total, long current, boolean isDownloading) { + netOnLoading(total, current, isDownloading); + } + + @Override + public void onSuccess(String result) { + + Logger.json(result); + JsonBean jsonBean = null; + try { +// jsonBean = JSON.parseObject(result, JsonBean.class); + jsonBean = jsonParse(result); + if (jsonBean.getMsg() != null && !jsonBean.getMsg().isEmpty()) { + showToast(jsonBean.getMsg()); + } + if (jsonBean.getCode() == 200) { + Map data = new ArrayMap(); + if (null != jsonBean.getData() && jsonBean.getData().size() > 0) { + data = jsonBean.getData(); + } + netOnSuccess(data); + } else { + + netOnOtherStates(jsonBean.getCode(), jsonBean.getMsg()); + } + } catch (Exception e) { + if (loadingDialog != null && loadingDialog.isShowing()) { + loadingDialog.dismiss(); + } + Logger.d(result); + showToast("服务器异常!"); + e.printStackTrace(); + } finally { + } + } + + @Override + public void onError(Throwable ex, boolean isOnCallback) { + netOnFailure(ex); + + } + + @Override + public void onCancelled(CancelledException cex) { + Logger.d("用户取消了访问网络...."); + netOnCancelled(); + } + + @Override + public void onFinished() { + netOnFinish(); + } + + }); + } + + + private JsonBean jsonParse(String json) throws JSONException { + ArrayMap arrayMap= JSON.parseObject(json,new TypeReference>(){ + }.getType()); + JsonBean jsonBean = new JsonBean(); + if (arrayMap.containsKey("data")) { + Object data = arrayMap.get("data"); + System.out.println("data.getClass().getName()=" + data.getClass().getName()); + ArrayMap rrData = null; + if (data instanceof String) { + System.out.println("data instanceof String"); + rrData = new ArrayMap(); + rrData.put("data", data.toString()); + } else if (data instanceof JSONArray) { + System.out.println("data instanceof JSONArray"); + rrData = new ArrayMap(); + rrData.put("data", data); + } else if (data instanceof com.alibaba.fastjson.JSONObject) { + System.out.println("data instanceof JSONObject"); + rrData = JSON.parseObject(data.toString(),new TypeReference>(){ + }.getType()); + } + jsonBean.setData(rrData); + } + jsonBean.setCode(Integer.valueOf(arrayMap.get("code").toString())); + jsonBean.setMsg(Tools.getValue(arrayMap, "msg")); + + return jsonBean; + } + + + /** + * 开始访问网络 + */ + public void netOnStart() { + loadingDialog.show("正在获取数据..."); + } + + /** + * 访问网络的进程 + */ + public void netOnLoading(long total, long current, boolean isUploading) { + } + + /** + * 访问网络成功 + */ + public void netOnSuccess(Map data) { + if (loadingDialog != null) { + loadingDialog.dismiss(); + } + } + + /** + * 访问网络成功的其他状态 + */ + public void netOnOtherStates(int code, String msg) { + if (loadingDialog != null) { + loadingDialog.dismiss(); + } + } + + /** + * 访问网络结束 + */ + public void netOnFinish() { + loadingDialog.dismiss(); + } + + /** + * 访问网络失败 + */ + public void netOnFailure(Throwable ex) { + if (loadingDialog != null) { + loadingDialog.dismiss(); + } + Logger.d(ex.getMessage()); + if (ex instanceof HttpException) { // 网络错误 + HttpException httpEx = (HttpException) ex; + int responseCode = httpEx.getCode(); + String responseMsg = httpEx.getMessage(); + String errorResult = httpEx.getResult(); + Toast.makeText(x.app(), "网络错误:" + ex.getMessage(), Toast.LENGTH_LONG).show(); + // ... + } else { // 其他错误 + Toast.makeText(context, "连接服务器失败,请稍后再试!ex=" + ex.getMessage(), Toast.LENGTH_SHORT).show(); + // ... + } + + + } + + /** + * 取消访问网络 + */ + public void netOnCancelled() { + if (loadingDialog != null) { + loadingDialog.dismiss(); + } + } + + @Override + public void onBackPressed() { +// Logger.d("onBackPressed"); + if (loadingDialog != null && loadingDialog.isShowing()) { + loadingDialog.dismiss(); + + if (cancelable != null && !cancelable.isCancelled()) { + cancelable.cancel(); + } + } else { + super.onBackPressed(); + } + + } + + protected void setEmptyView(ListView listView) { + TextView emptyView = new TextView(context); + emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + emptyView.setText("暂无数据!"); + emptyView.setGravity(Gravity.CENTER); + emptyView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); + emptyView.setVisibility(View.GONE); + ((ViewGroup) listView.getParent()).addView(emptyView); + listView.setEmptyView(emptyView); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + mContentLayout.removeAllViews(); + mContentLayout=null; + AppManager.getAppManager().finishActivity(this); + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + if (null != this.getCurrentFocus()) { + /** + * 点击空白位置 隐藏软键盘 + */ + InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); + return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0); + } + return super.onTouchEvent(event); + } +} + diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/base/BaseFragment.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/base/BaseFragment.java new file mode 100644 index 0000000..bd3d2fd --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/base/BaseFragment.java @@ -0,0 +1,368 @@ +package com.kejiang.yuandl.base; + +import android.support.v4.app.Fragment; +import android.support.v4.util.ArrayMap; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.TypeReference; +import com.kejiang.yuandl.app.MyApplication; +import com.kejiang.yuandl.bean.JsonBean; +import com.kejiang.yuandl.utils.CheckNetwork; +import com.kejiang.yuandl.utils.Tools; +import com.kejiang.yuandl.view.LoadingDialog; +import com.orhanobut.logger.Logger; +import com.squareup.leakcanary.RefWatcher; + +import org.xutils.common.Callback; +import org.xutils.common.util.KeyValue; +import org.xutils.common.util.MD5; +import org.xutils.ex.HttpException; +import org.xutils.http.RequestParams; +import org.xutils.x; + +import java.util.List; +import java.util.Map; + +/** + * com.bm.falvzixun.fragment.BaseFragment + * + * @author yuandl on 2016/1/15. + * 描述主要干什么 + */ +public class BaseFragment extends Fragment { + private Callback.Cancelable cancelable; + /** + * 加载数据对话框 + */ + public LoadingDialog loadingDialog; + + /** + * 异步网络请求类 + * + * @param requestParams + */ + protected void ajax(RequestParams requestParams) { + if (!CheckNetwork.isNetworkAvailable(getContext())) { + showToast("网络不可用,请检查网络连接!"); + return; + } + if (loadingDialog == null) { + loadingDialog = new LoadingDialog(getContext()); + } + if (requestParams != null) { + String uri = requestParams.getUri(); + if (!uri.isEmpty()) { + String[] split = uri.split("/"); +// Logger.d("split=" + Arrays.toString(split)); + String method = split[split.length - 1].substring(0, split[split.length - 1].indexOf(".")); + String mode = split[split.length - 2]; + String sign = MD5.md5(mode + method); + requestParams.addBodyParameter("sign", sign); + } + + } + Logger.d("url=" + requestParams.getUri() + "\nrequestParams=" + requestParams.getStringParams().toString()); + List params = requestParams.getStringParams(); + for (KeyValue keyValue : params) { + if (keyValue.key.contains(":")) { + throw new RuntimeException("参数异常!"); + } + } + // jsonBean = JSON.parseObject(result, JsonBean.class); + cancelable = x.http().post(requestParams, new Callback.ProgressCallback() { + + @Override + public void onWaiting() { + } + + @Override + + public void onStarted() { + netOnStart(); + } + + @Override + public void onLoading(long total, long current, boolean isDownloading) { + netOnLoading(total, current, isDownloading); + } + + @Override + public void onSuccess(String result) { + Logger.json(result); + JsonBean jsonBean = null; + try { +// jsonBean = JSON.parseObject(result, JsonBean.class); + jsonBean = jsonParse(result); + if (jsonBean.getMsg() != null && !jsonBean.getMsg().isEmpty()) { + showToast(jsonBean.getMsg()); + } + if (jsonBean.getCode() == 200) { + Map data = new ArrayMap(); + if (null != jsonBean.getData() && jsonBean.getData().size() > 0) { + data = jsonBean.getData(); + } + netOnSuccess(data); + } else { + + netOnOtherStates(jsonBean.getCode(), jsonBean.getMsg()); + } + } catch (Exception e) { + if (loadingDialog != null && loadingDialog.isShowing()) { + loadingDialog.dismiss(); + } + Logger.d(result); + showToast("服务器异常!"); + e.printStackTrace(); + } finally { + } + } + + @Override + public void onError(Throwable ex, boolean isOnCallback) { + netOnFailure(ex); + + } + + @Override + public void onCancelled(CancelledException cex) { + Logger.d("用户取消了访问网络...."); + netOnCancelled(); + } + + @Override + public void onFinished() { + netOnFinish(); + } + + }); + } +// +// private JsonBean jsonParse(String json) throws JSONException { +// Map map = JSON.parseObject(json, new TypeToken>() { +// }.getType()); +// JsonBean jsonBean = new JsonBean(); +// if (map.containsKey("data")) { +// Object data = map.get("data"); +// System.out.println("data.getClass().getName()=" + data.getClass().getName()); +// Map rrData = null; +// if (data instanceof String) { +// System.out.println("data instanceof String"); +// rrData = new HashMap<>(); +// rrData.put("data", data.toString()); +// } else if (data instanceof JSONArray) { +// System.out.println("data instanceof JSONArray"); +// rrData = new HashMap<>(); +// rrData.put("data", data); +// } else if (data instanceof com.alibaba.fastjson.JSONObject) { +// System.out.println("data instanceof JSONObject"); +// rrData = (Map) data; +// } +// jsonBean.setData(rrData); +// } +// jsonBean.setCode(Integer.valueOf(map.get("code").toString())); +// jsonBean.setMsg(Tools.getValue(map, "msg")); +// +// return jsonBean; +// } + + private JsonBean jsonParse(String json) throws JSONException { + ArrayMap arrayMap= JSON.parseObject(json,new TypeReference>(){ + }.getType()); + JsonBean jsonBean = new JsonBean(); + if (arrayMap.containsKey("data")) { + Object data = arrayMap.get("data"); + System.out.println("data.getClass().getName()=" + data.getClass().getName()); + ArrayMap rrData = null; + if (data instanceof String) { + System.out.println("data instanceof String"); + rrData = new ArrayMap(); + rrData.put("data", data.toString()); + } else if (data instanceof JSONArray) { + System.out.println("data instanceof JSONArray"); + rrData = new ArrayMap(); + rrData.put("data", data); + } else if (data instanceof com.alibaba.fastjson.JSONObject) { + System.out.println("data instanceof JSONObject"); + rrData = JSON.parseObject(data.toString(),new TypeReference>(){ + }.getType()); + } + jsonBean.setData(rrData); + } + jsonBean.setCode(Integer.valueOf(arrayMap.get("code").toString())); + jsonBean.setMsg(Tools.getValue(arrayMap, "msg")); + + return jsonBean; + } + /** + * 开始访问网络 + */ + public void netOnStart() { + loadingDialog.show("正在请求网络..."); + } + + /** + * 访问网络的进程 + */ + public void netOnLoading(long total, long current, boolean isUploading) { + } + + /** + * 访问网络成功 + */ + public void netOnSuccess(Map data) { + + } + + /** + * 访问网络成功的其他状态 + */ + public void netOnOtherStates(int code, String msg) { + if (loadingDialog != null && loadingDialog.isShowing()) { + loadingDialog.dismiss(); + } + } + + /** + * 访问网络结束 + */ + public void netOnFinish() { + loadingDialog.dismiss(); + } + + /** + * 访问网络失败 + */ + public void netOnFailure(Throwable ex) { + Logger.d(ex.getMessage()); + if (ex instanceof HttpException) { // 网络错误 + HttpException httpEx = (HttpException) ex; + int responseCode = httpEx.getCode(); + String responseMsg = httpEx.getMessage(); + String errorResult = httpEx.getResult(); + Toast.makeText(x.app(), "网络错误:" + ex.getMessage(), Toast.LENGTH_LONG).show(); + // ... + } else { // 其他错误 + Toast.makeText(x.app(), "连接服务器失败,请稍后再试!ex=" + ex.getMessage(), Toast.LENGTH_SHORT).show(); + // ... + } + + + } + + /** + * 取消访问网络 + */ + public void netOnCancelled() { + } + + + // /** +// * 弹出Toast便捷方法 +// * +// * @param charSequence +// */ +// public void showToast(CharSequence charSequence) { +// Toast.makeText(getContext(), charSequence, Toast.LENGTH_SHORT).show(); +// +// } + private Toast toast; + + /** + * 弹出Toast便捷方法 + * + * @param charSequence + */ + public void showToast(CharSequence charSequence) { + if (null == toast) { + toast = Toast.makeText(x.app(), charSequence, Toast.LENGTH_SHORT); + } else { + toast.setText(charSequence); + } + toast.show(); + + } + + @Override + public void onPause() { + super.onPause(); + if (null != toast) { + toast.cancel(); + } + + } + + /** + * Fragment当前状态是否可见 + */ + protected boolean isVisible; + + protected boolean isLoadData = false; + protected boolean isPrepared = false; + + @Override + public void setUserVisibleHint(boolean isVisibleToUser) { + super.setUserVisibleHint(isVisibleToUser); + + if (getUserVisibleHint()) { + isVisible = true; + onVisible(); + } else { + isVisible = false; + onInvisible(); + } + } + + + /** + * 可见 + */ + protected void onVisible() { + lazyLoad(); + } + + + /** + * 不可见 + */ + protected void onInvisible() { + + + } + + + /** + * 延迟加载 + * 子类必须重写此方法 + */ + protected void lazyLoad() { + + } + + protected void setEmptyView(ListView listView) { + TextView emptyView = new TextView(getContext()); + emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + emptyView.setText("暂无数据!"); + emptyView.setGravity(Gravity.CENTER); + emptyView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); + emptyView.setVisibility(View.GONE); + ((ViewGroup) listView.getParent()).addView(emptyView); + listView.setEmptyView(emptyView); + listView.setVisibility(View.VISIBLE); + } + + @Override + public void onDestroy() { + super.onDestroy(); + RefWatcher refWatcher = MyApplication.getRefWatcher(getActivity()); + refWatcher.watch(this); + } +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/bean/JsonBean.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/bean/JsonBean.java new file mode 100644 index 0000000..c28d36a --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/bean/JsonBean.java @@ -0,0 +1,48 @@ +package com.kejiang.yuandl.bean; + +import java.util.Map; + +/** + * com.bm.falvzixun.bean.GsonBean + * + * @author yuandl on 2016/1/4. + * json解析工具类对象 + */ +public class JsonBean { + private int code; + private String msg; + private Map data; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public Map getData() { + return data; + } + + public void setData(Map data) { + this.data = data; + } + + @Override + public String toString() { + return "JsonBean{" + + "code=" + code + + ", msg='" + msg + '\'' + + ", data=" + data + + '}'; + } +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/AppManager.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/AppManager.java new file mode 100644 index 0000000..43e450b --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/AppManager.java @@ -0,0 +1,228 @@ +package com.kejiang.yuandl.utils; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; + +import java.util.ArrayList; +import java.util.Stack; + +/** + * activity 管理类 + * + * @author dylan + */ +public class AppManager { + + private static Stack activityStack; + private static AppManager instance; + + private AppManager() { + activityStack = new Stack(); + } + + /** + * 单一实例 + */ + public static AppManager getAppManager() { + if (instance == null) { + instance = new AppManager(); + } + return instance; + } + + /** + * 栈中是否为空 + * + * @return + */ + public boolean isEmpty() { + return activityStack.isEmpty(); + } + + /** + * 添加Activity到堆栈 + */ + public void addActivity(Activity activity) { + activityStack.add(activity); + } + + /** + * 获取当前Activity(堆栈中最后一个压入的) + */ + public Activity currentActivity() { + if (activityStack.isEmpty()) { + return null; + } + Activity activity = activityStack.lastElement(); + return activity; + } + + /** + * 获取前一个activity,便于返回 + * + * @return + */ + public Activity lastActivity() { + if (activityStack.size() < 2) { + return null; + } + return activityStack.get(activityStack.size() - 1); + } + + /** + * 结束当前Activity(堆栈中最后一个压入的) + */ + public void finishActivity() { + if (activityStack.empty()) { + return; + } + Activity activity = activityStack.lastElement(); + finishActivity(activity); + } + + /** + * 从栈中移除指定的Activity + * + * @param activity + */ + public void removeActivity(Activity activity) { + if (activity != null) { + activityStack.remove(activity); + } + } + + /** + * 结束指定的Activity + */ + public void finishActivity(Activity activity) { + if (activity != null) { + if (activityStack.remove(activity)) { + activity.finish(); + } + } + // 隐藏上一个页面的键盘 + /* + * if(activityStack.size() > 0){ + * UIUtils.alwaysHideSoftKeyboard(activityStack.peek()); } + */ + } + + /** + * 结束指定类名的Activity + */ + public void finishActivity(Class cls) { + for (Activity activity : activityStack) { + if (activity.getClass().equals(cls)) { + finishActivity(activity); + } + } + } + + /** + * 结束所有Activity + */ + public void finishAllActivity() { + ArrayList activityList = new ArrayList( + activityStack); + for (int i = 0, size = activityList.size(); i < size; i++) { + if (null != activityList.get(i)) { + activityList.get(i).finish(); + } + } + activityStack.clear(); + } + + /** + * 结束所有Activity保留主界面 + */ + public void finishAllActivityExcludeMain() { + + int stackSize = activityStack.size(); + + if (stackSize >= 1) { + + ArrayList activityList = new ArrayList( + activityStack.subList(1, stackSize)); + + for (int i = 0, size = activityList.size(); i < size; i++) { + + Activity activity = activityList.get(i); + + if (activity != null) { + + activity.finish(); + + activityStack.remove(activity); + } + } + } + } + /** + * 结束所有Activity保留登录界面 + */ + public void finishAllActivityExcludeLogin() { + ArrayList activityList = new ArrayList( + activityStack); + for (int i = 0, size = activityList.size(); i < size; i++) { + Activity activity = activityList.get(i); + if (null != activityList.get(i)) { + if(!activityList.get(i).getClass().getSimpleName().equals("UserSetActivity")) { + activityList.get(i).finish(); + activityStack.remove(activity); + } + } + } + } + /** + * 退出应用程序 + */ + public void AppExit(Context context) { + try { + finishAllActivity(); +// MyApplication.getInstance().unregisterReceiver(); + /* + * ActivityManager activityMgr= (ActivityManager) + * context.getSystemService(Context.ACTIVITY_SERVICE); + * activityMgr.restartPackage(context.getPackageName()); + */ + // System.exit(0); + + } catch (Exception e) { + } + } + + /** + * 退出应用程序并停止服务 + */ + public void AppExit(Context context, Intent intent) { + try { + context.stopService(intent); + finishAllActivity(); + } catch (Exception e) { + } + } + + public void dataReset(Context context) { +// UserInfo.getInstance(context).clear(); +// MyApplication.getInstance().getLockPatternUtils().clearLock(); +// GesturesPassword.getInstance(context).clear(); +//// ajax(RequestURl.logoutURl, null); +// DbUtils db = DbUtils.create(context); +// try { +// db.deleteAll(Menu_Top.class); +// db.deleteAll(Menu_Center.class); +// db.deleteAll(News.class); +// db.deleteAll(Notice.class); +// db.deleteAll(PhoneList.class); +// db.deleteAll(Project.class); +// db.deleteAll(ProjectPersons.class); +// db.deleteAll(ProjectPlan.class); +// db.deleteAll(Todo.class); +// db.deleteAll(Leave.class); +// db.deleteAll(WeekPlans.class); +// } catch (DbException e) { +// e.printStackTrace(); +// } + } +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/Base64.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/Base64.java new file mode 100644 index 0000000..1a327c1 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/Base64.java @@ -0,0 +1,294 @@ +/* + * Copyright (C) 2010 The MobileSecurePay Project + * All right reserved. + * author: shiqun.shi@alipay.com + */ + +package com.kejiang.yuandl.utils; + +/** + * Base64 工具�? + * + */ +public final class Base64 { + + static private final int BASELENGTH = 128; + static private final int LOOKUPLENGTH = 64; + static private final int TWENTYFOURBITGROUP = 24; + static private final int EIGHTBIT = 8; + static private final int SIXTEENBIT = 16; + static private final int FOURBYTE = 4; + static private final int SIGN = -128; + static private final char PAD = '='; + static private final boolean fDebug = false; + static final private byte[] base64Alphabet = new byte[BASELENGTH]; + static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; + + static { + for (int i = 0; i < BASELENGTH; ++i) { + base64Alphabet[i] = -1; + } + for (int i = 'Z'; i >= 'A'; i--) { + base64Alphabet[i] = (byte) (i - 'A'); + } + for (int i = 'z'; i >= 'a'; i--) { + base64Alphabet[i] = (byte) (i - 'a' + 26); + } + + for (int i = '9'; i >= '0'; i--) { + base64Alphabet[i] = (byte) (i - '0' + 52); + } + + base64Alphabet['+'] = 62; + base64Alphabet['/'] = 63; + + for (int i = 0; i <= 25; i++) { + lookUpBase64Alphabet[i] = (char) ('A' + i); + } + + for (int i = 26, j = 0; i <= 51; i++, j++) { + lookUpBase64Alphabet[i] = (char) ('a' + j); + } + + for (int i = 52, j = 0; i <= 61; i++, j++) { + lookUpBase64Alphabet[i] = (char) ('0' + j); + } + lookUpBase64Alphabet[62] = '+'; + lookUpBase64Alphabet[63] = '/'; + + } + + private static boolean isWhiteSpace(char octect) { + return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); + } + + private static boolean isPad(char octect) { + return (octect == PAD); + } + + private static boolean isData(char octect) { + return (octect < BASELENGTH && base64Alphabet[octect] != -1); + } + + /** + * Encodes hex octects into Base64 + * + * @param binaryData + * Array containing binaryData + * @return Encoded Base64 array + */ + public static String encode(byte[] binaryData) { + + if (binaryData == null) { + return null; + } + + int lengthDataBits = binaryData.length * EIGHTBIT; + if (lengthDataBits == 0) { + return ""; + } + + int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; + int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; + int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 + : numberTriplets; + char encodedData[] = null; + + encodedData = new char[numberQuartet * 4]; + + byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; + + int encodedIndex = 0; + int dataIndex = 0; + if (fDebug) { + System.out.println("number of triplets = " + numberTriplets); + } + + for (int i = 0; i < numberTriplets; i++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + if (fDebug) { + System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3); + } + + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) + : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) + : (byte) ((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) + : (byte) ((b3) >> 6 ^ 0xfc); + + if (fDebug) { + System.out.println("val2 = " + val2); + System.out.println("k4 = " + (k << 4)); + System.out.println("vak = " + (val2 | (k << 4))); + } + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + } + + // form integral number of 6-bit groups + if (fewerThan24bits == EIGHTBIT) { + b1 = binaryData[dataIndex]; + k = (byte) (b1 & 0x03); + if (fDebug) { + System.out.println("b1=" + b1); + System.out.println("b1<<2 = " + (b1 >> 2)); + } + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) + : (byte) ((b1) >> 2 ^ 0xc0); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; + encodedData[encodedIndex++] = PAD; + encodedData[encodedIndex++] = PAD; + } else if (fewerThan24bits == SIXTEENBIT) { + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex + 1]; + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) + : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) + : (byte) ((b2) >> 4 ^ 0xf0); + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex++] = PAD; + } + + return new String(encodedData); + } + + /** + * Decodes Base64 data into octects + * + * @param encoded + * string containing Base64 data + * @return Array containind decoded data. + */ + public static byte[] decode(String encoded) { + + if (encoded == null) { + return null; + } + + char[] base64Data = encoded.toCharArray(); + // remove white spaces + int len = removeWhiteSpace(base64Data); + + if (len % FOURBYTE != 0) { + return null;// should be divisible by four + } + + int numberQuadruple = (len / FOURBYTE); + + if (numberQuadruple == 0) { + return new byte[0]; + } + + byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; + char d1 = 0, d2 = 0, d3 = 0, d4 = 0; + + int i = 0; + int encodedIndex = 0; + int dataIndex = 0; + decodedData = new byte[(numberQuadruple) * 3]; + + for (; i < numberQuadruple - 1; i++) { + + if (!isData((d1 = base64Data[dataIndex++])) + || !isData((d2 = base64Data[dataIndex++])) + || !isData((d3 = base64Data[dataIndex++])) + || !isData((d4 = base64Data[dataIndex++]))) { + return null; + }// if found "no data" just return null + + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + + decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); + } + + if (!isData((d1 = base64Data[dataIndex++])) + || !isData((d2 = base64Data[dataIndex++]))) { + return null;// if found "no data" just return null + } + + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + + d3 = base64Data[dataIndex++]; + d4 = base64Data[dataIndex++]; + if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { + if ((b2 & 0xf) != 0)// last 4 bits should be zero + { + return null; + } + byte[] tmp = new byte[i * 3 + 1]; + System.arraycopy(decodedData, 0, tmp, 0, i * 3); + tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); + return tmp; + } else if (!isPad(d3) && isPad(d4)) { + b3 = base64Alphabet[d3]; + if ((b3 & 0x3) != 0)// last 2 bits should be zero + { + return null; + } + byte[] tmp = new byte[i * 3 + 2]; + System.arraycopy(decodedData, 0, tmp, 0, i * 3); + tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); + tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + return tmp; + } else { + return null; + } + } else { // No PAD e.g 3cQl + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); + + } + return decodedData; + } + + /** + * remove WhiteSpace from MIME containing encoded Base64 data. + * + * @param data + * the byte array of base64 data (with WS) + * @return the new length + */ + private static int removeWhiteSpace(char[] data) { + if (data == null) { + return 0; + } + + // count characters that's not whitespace + int newSize = 0; + int len = data.length; + for (int i = 0; i < len; i++) { + if (!isWhiteSpace(data[i])) { + data[newSize++] = data[i]; + } + } + return newSize; + } +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/CheckNetwork.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/CheckNetwork.java new file mode 100644 index 0000000..3549765 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/CheckNetwork.java @@ -0,0 +1,84 @@ +package com.kejiang.yuandl.utils; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; + + +public class CheckNetwork { + + public CheckNetwork() { + // TODO Auto-generated constructor stub + } + +// /** +// * 检测网络是否可用 +// * +// * @return 是否可用 +// */ +// public static boolean isNetworkAvailable(Context context) { +// ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); +// NetworkInfo ni = cm.getActiveNetworkInfo(); +// return (ni != null && ni.isAvailable()); +// } + /** + * 检测当的网络(WLAN、3G/2G)状态 + * @param context Context + * @return true 表示网络可用 + */ + public static boolean isNetworkAvailable(Context context) { +// ConnectivityManager connectivity = (ConnectivityManager) context +// .getSystemService(Context.CONNECTIVITY_SERVICE); +// if (connectivity != null) { +// NetworkInfo info = connectivity.getActiveNetworkInfo(); +// if (info != null && info.isConnected()) +// { +// // 当前网络是连接的 +// if (info.getState() == NetworkInfo.State.CONNECTED) +// { +// // 当前所连接的网络可用 +// return true; +// } +// } +// } +// return false; + if (context != null) { + ConnectivityManager mConnectivityManager = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); + if (mNetworkInfo != null) { + return mNetworkInfo.isAvailable(); + } + } + return false; + } + + /** + * 判断是否为wifi网络链接 + * + * @param context + * @return + */ + public static boolean isWifi(Context context) { + ConnectivityManager connectivityManager = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); + return activeNetInfo != null + && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI; + } + + /** + * 判断当前网络是否是3G网络 + * + * @param context + * @return boolean + */ + public static boolean is3G(Context context) { + ConnectivityManager connectivityManager = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); + return activeNetInfo != null + && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE; + } + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/DisplayUtil.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/DisplayUtil.java new file mode 100644 index 0000000..7d33c6a --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/DisplayUtil.java @@ -0,0 +1,70 @@ +package com.kejiang.yuandl.utils; + +/** + * ToDo 描述主要干什么 + * Author: dylan + * Date: 2015-03-04 + * Time: 11:09 + */ + +import android.content.Context; + +/** + * dp、sp 转换为 px 的工具类 + * + * @author fxsky 2012.11.12 + * + */ +public class DisplayUtil { + /** + * 将px值转换为dip或dp值,保证尺寸大小不变 + * + * @param pxValue + * @param scale + * (DisplayMetrics类中属性density) + * @return + */ + public static int px2dip(Context context, float pxValue) { + final float scale = context.getResources().getDisplayMetrics().density; + return (int) (pxValue / scale + 0.5f); + } + + /** + * 将dip或dp值转换为px值,保证尺寸大小不变 + * + * @param dipValue + * @param scale + * (DisplayMetrics类中属性density) + * @return + */ + public static int dip2px(Context context, float dipValue) { + final float scale = context.getResources().getDisplayMetrics().density; + return (int) (dipValue * scale + 0.5f); + } + + /** + * 将px值转换为sp值,保证文字大小不变 + * + * @param pxValue + * @param fontScale + * (DisplayMetrics类中属性scaledDensity) + * @return + */ + public static int px2sp(Context context, float pxValue) { + final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; + return (int) (pxValue / fontScale + 0.5f); + } + + /** + * 将sp值转换为px值,保证文字大小不变 + * + * @param spValue + * @param fontScale + * (DisplayMetrics类中属性scaledDensity) + * @return + */ + public static int sp2px(Context context, float spValue) { + final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; + return (int) (spValue * fontScale + 0.5f); + } +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/DownloadImgUtils.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/DownloadImgUtils.java new file mode 100644 index 0000000..c8cd7f8 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/DownloadImgUtils.java @@ -0,0 +1,196 @@ +package com.kejiang.yuandl.utils; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.BitmapFactory.Options; +import android.widget.ImageView; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * http://blog.csdn.net/lmj623565791/article/details/41874561 + * @author zhy + * + */ +public class DownloadImgUtils +{ + + /** + * 根据url下载图片在指定的文件 + * + * @param urlStr + * @param file + * @return + */ + public static boolean downloadImgByUrl(String urlStr, File file) + { + FileOutputStream fos = null; + InputStream is = null; + try + { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + + is = conn.getInputStream(); + fos = new FileOutputStream(file); + byte[] buf = new byte[512]; + int len = 0; + while ((len = is.read(buf)) != -1) + { + fos.write(buf, 0, len); + } + fos.flush(); + return true; + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (is != null) + is.close(); + } catch (IOException e) + { + } + + try + { + if (fos != null) + fos.close(); + } catch (IOException e) + { + } + } + + return false; + + } + + /** + * 根据url下载图片在指定的文件 + * + * @param urlStr + * @param file + * @return + */ + public static Bitmap downloadImgByUrl(String urlStr, ImageView imageview) + { + FileOutputStream fos = null; + InputStream is = null; + try + { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + is = new BufferedInputStream(conn.getInputStream()); + is.mark(is.available()); + + Options opts = new Options(); + opts.inJustDecodeBounds = true; + Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts); + + //获取imageview想要显示的宽和高 + ImageSizeUtil.ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview); + opts.inSampleSize = ImageSizeUtil.caculateInSampleSize(opts, + imageViewSize.width, imageViewSize.height); + + opts.inJustDecodeBounds = false; + is.reset(); + bitmap = BitmapFactory.decodeStream(is, null, opts); + + conn.disconnect(); + return bitmap; + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (is != null) + is.close(); + } catch (IOException e) + { + } + + try + { + if (fos != null) + fos.close(); + } catch (IOException e) + { + } + } + + return null; + + } +/** + * 根据url下载图片在指定的文件 + * + * @param urlStr + * @param file + * @return + */ + public static Bitmap downloadImgByUrl(String urlStr) + { + FileOutputStream fos = null; + InputStream is = null; + try + { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + is = new BufferedInputStream(conn.getInputStream()); + is.mark(is.available()); + + Options opts = new Options(); + opts.inJustDecodeBounds = true; + Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts); + +// //获取imageview想要显示的宽和高 +// ImageSizeUtil.ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview); +// opts.inSampleSize = ImageSizeUtil.caculateInSampleSize(opts, +// imageViewSize.width, imageViewSize.height); + + opts.inJustDecodeBounds = false; + is.reset(); + bitmap = BitmapFactory.decodeStream(is, null, opts); + + conn.disconnect(); + return bitmap; + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (is != null) + is.close(); + } catch (IOException e) + { + } + + try + { + if (fos != null) + fos.close(); + } catch (IOException e) + { + } + } + + return null; + + } + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/FileUtill.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/FileUtill.java new file mode 100644 index 0000000..24e7e4a --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/FileUtill.java @@ -0,0 +1,223 @@ +package com.kejiang.yuandl.utils; + +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Environment; +import android.widget.Toast; + +import com.orhanobut.logger.Logger; + +import java.io.File; +import java.text.DecimalFormat; + +/** + * ToDo 描述主要干什么 + * Author: dylan + * Date: 2015-01-05 + * Time: 09:37 + */ +public class FileUtill { + + + // 有SD卡路径-临时 + public final static String phonePathTemporary = Environment + .getExternalStorageDirectory().getPath() + "/rtCloudTemporary/Image/"; + // 无SD卡时图片路径-临时 + public static String noSDCardPhonePathTemporary = "/rtCloudTemporary/Image/"; + + // 有SD卡路径Temporary + public final static String phonePath = Environment + .getExternalStorageDirectory().getPath() + "/rtCloud/Image/"; + // 无SD卡时图片路径 + public static String noSDCardPhonePath = "/rtCloud/Image/"; + + + public static String newFile(String dir, String name) { + if (isSdCardMounted()) { + File fileDir = new File(dir); + // 是否有这个文件夹,没有就创建 + if (!fileDir.exists()) + fileDir.mkdirs(); + File file = new File(dir, name); + return ""; + } else { + return "Sd卡不可用!"; + } + + } + + /** + * sd卡挂载且可用 + * + * @return + */ + public static boolean isSdCardMounted() { + return Environment.getExternalStorageState().equals( + Environment.MEDIA_MOUNTED); + } + + /** + * @param @return 设定文件 + * @return String 返回类型 + * @throws + * @Title: getImageParentsPathTemporary + * @Description: 临时路径 + */ + public static String getImageParentsPathTemporary() { + if (isSdCardMounted()) { + return phonePathTemporary; + } else { + return noSDCardPhonePathTemporary; + } + } + + + public static void openFile(Context context, File file) { + + Intent intent = new Intent(); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent.setAction(Intent.ACTION_VIEW); + String type = getMIMEType(file); + intent.setDataAndType(Uri.fromFile(file), type); + Logger.d("Uri.fromFile(file) " + Uri.fromFile(file)); + Logger.d("type " + type); + try { + context.startActivity(intent); + } catch (Exception e) { + e.printStackTrace(); + Toast.makeText(context, "打开失败,请安装支持打开该类文件的应用。", Toast.LENGTH_LONG).show(); + } + + + } + + /** + * 根据文件后缀名获得对应的MIME类型。 + * + * @param file + */ + private static String getMIMEType(File file) { + + String type = "*/*"; + String fName = file.getName(); + int dotIndex = fName.lastIndexOf("."); + if (dotIndex < 0) { + return type; + } + String end = fName.substring(dotIndex, fName.length()).toLowerCase(); + if (end == "") return type; + for (int i = 0; i < MIME_MapTable.length; i++) { + if (end.equals(MIME_MapTable[i][0])) + type = MIME_MapTable[i][1]; + } + return type; + } + + private static final String[][] MIME_MapTable = { + // {后缀名, MIME类型} + {".3gp", "video/3gpp"}, + {".apk", "applicationnd.android.package-archive"}, + {".asf", "video/x-ms-asf"}, + {".avi", "video/x-msvideo"}, + {".bin", "application/octet-stream"}, + {".bmp", "image/bmp"}, + {".c", "text/plain"}, + {".class", "application/octet-stream"}, + {".conf", "text/plain"}, + {".cpp", "text/plain"}, + {".doc", "application/msword"}, + {".docx", + "applicationnd.openxmlformats-officedocument.wordprocessingml.document"}, + {".xls", "applicationnd.ms-excel"}, + {".xlsx", + "applicationnd.openxmlformats-officedocument.spreadsheetml.sheet"}, + {".exe", "application/octet-stream"}, + {".gif", "image/gif"}, + {".gtar", "application/x-gtar"}, + {".gz", "application/x-gzip"}, + {".h", "text/plain"}, + {".htm", "textml"}, + {".html", "textml"}, + {".jar", "application/java-archive"}, + {".java", "text/plain"}, + {".jpeg", "image/jpeg"}, + {".jpg", "image/jpeg"}, + {".js", "application/x-javascript"}, + {".log", "text/plain"}, + {".m3u", "audio/x-mpegurl"}, + {".m4a", "audio/mp4a-latm"}, + {".m4b", "audio/mp4a-latm"}, + {".m4p", "audio/mp4a-latm"}, + {".m4u", "videond.mpegurl"}, + {".m4v", "video/x-m4v"}, + {".mov", "video/quicktime"}, + {".mp2", "audio/x-mpeg"}, + {".mp3", "audio/x-mpeg"}, + {".mp4", "video/mp4"}, + {".mpc", "applicationnd.mpohun.certificate"}, + {".mpe", "video/mpeg"}, + {".mpeg", "video/mpeg"}, + {".mpg", "video/mpeg"}, + {".mpg4", "video/mp4"}, + {".mpga", "audio/mpeg"}, + {".msg", "applicationnd.ms-outlook"}, + {".ogg", "audio/ogg"}, + {".pdf", "applicationf"}, + {".png", "image/png"}, + {".pps", "applicationnd.ms-powerpoint"}, + {".ppt", "applicationnd.ms-powerpoint"}, + {".pptx", "applicationnd.openxmlformats-officedocument.presentationml.presentation"}, + {".prop", "text/plain"}, {".rc", "text/plain"}, + {".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"}, + {".sh", "text/plain"}, {".tar", "application/x-tar"}, + {".tgz", "application/x-compressed"}, {".txt", "text/plain"}, + {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"}, + {".wmv", "audio/x-ms-wmv"}, + {".wps", "applicationnd.ms-works"}, {".xml", "text/plain"}, + {".z", "application/x-compress"}, + {".zip", "application/x-zip-compressed"}, {"", "*/*"}}; + + /** + * @param @param fileS + * @param @return 设定文件 + * @return String 返回类型 + * @throws + * @Title: FormetFileSize + * @Description: 转换文件大小 + */ + public static String FormetFileSize(long fileS) { + DecimalFormat df = new DecimalFormat("#.00"); + String fileSizeString = ""; + if (fileS < 1024) { + fileSizeString = df.format((double) fileS) + "B"; + } else if (fileS < 1048576) { + fileSizeString = df.format((double) fileS / 1024) + "KB"; + } else if (fileS < 1073741824) { + fileSizeString = df.format((double) fileS / 1048576) + "MB"; + } else { + fileSizeString = df.format((double) fileS / 1073741824) + "GB"; + } + return fileSizeString; + } + + +//删除文件和文件夹 + public static void delete(File file) { + if (file.isFile()) { + file.delete(); + return; + } + if (file.isDirectory()) { + File[] childFiles = file.listFiles(); + if (childFiles == null || childFiles.length == 0) { + file.delete(); + return; + } + for (int i = 0; i < childFiles.length; i++) { + delete(childFiles[i]); + } + file.delete(); + } + } +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageDispose.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageDispose.java new file mode 100644 index 0000000..e87b99f --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageDispose.java @@ -0,0 +1,119 @@ +package com.kejiang.yuandl.utils; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Matrix; +import android.media.ExifInterface; + +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +public class ImageDispose { + + /** + * 旋转图片 + * + * @param angle + * @param bitmap + * @return Bitmap + */ + public static Bitmap rotaingImageView(int angle, Bitmap bitmap) { + // 旋转图片 动作 + Matrix matrix = new Matrix(); + matrix.postRotate(angle); +// ShowMessageUtil.showPrint("旋转角度", angle); + // 创建新的图片 + Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, + bitmap.getWidth(), bitmap.getHeight(), matrix, true); + return resizedBitmap; + } + + /** + * 读取图片属性:旋转的角度 + * + * @param path 图片绝对路径 + * @return degree旋转的角度 + */ + public static int readPictureDegree(String path) { + int degree = 0; + try { + ExifInterface exifInterface = new ExifInterface(path); + int orientation = exifInterface.getAttributeInt( + ExifInterface.TAG_ORIENTATION, + ExifInterface.ORIENTATION_NORMAL); + switch (orientation) { + case ExifInterface.ORIENTATION_ROTATE_90: + degree = 90; + break; + case ExifInterface.ORIENTATION_ROTATE_180: + degree = 180; + break; + case ExifInterface.ORIENTATION_ROTATE_270: + degree = 270; + break; + } + } catch (IOException e) { + e.printStackTrace(); + } + return degree; + } + + /** + * 压缩图片 + */ + public static Bitmap compressImage(Bitmap image) { + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 + int options = 100; + while (baos.toByteArray().length / 1024 > 100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩 + baos.reset();//重置baos即清空baos + image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中 + options -= 10;//每次都减少10 + } + ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中 + Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片 + return bitmap; + } + + /** + * 设置显示的图片的比例大小 + * + * @param inSampleSize + * @return + */ + public static BitmapFactory.Options getBitmapOption(int inSampleSize) { + System.gc(); + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inPurgeable = true; + options.inSampleSize = 2; + return options; + } + + /** + * Bitmap对象保存味图片文件 + * + * @param path + * @param bitmap + */ + public static void saveBitmapFile(String path, Bitmap bitmap) { + File file = new File(path);// 将要保存图片的路径 + try { + BufferedOutputStream bos = new BufferedOutputStream( + new FileOutputStream(file)); + bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); + bos.flush(); + bos.close(); + if (bitmap != null) { + bitmap.recycle(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageLoader.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageLoader.java new file mode 100644 index 0000000..ec77408 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageLoader.java @@ -0,0 +1,461 @@ +package com.kejiang.yuandl.utils; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.Environment; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.support.v4.util.LruCache; +import android.util.Log; +import android.widget.ImageView; + +import java.io.File; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.LinkedList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; + +/** + * 图片加载类 + * http://blog.csdn.net/lmj623565791/article/details/41874561 + * @author zhy + * + */ +public class ImageLoader +{ + private static ImageLoader mInstance; + + /** + * 图片缓存的核心对象 + */ + private LruCache mLruCache; + /** + * 线程池 + */ + private ExecutorService mThreadPool; + private static final int DEAFULT_THREAD_COUNT = 1; + /** + * 队列的调度方式 + */ + private Type mType = Type.LIFO; + /** + * 任务队列 + */ + private LinkedList mTaskQueue; + /** + * 后台轮询线程 + */ + private Thread mPoolThread; + private Handler mPoolThreadHandler; + /** + * UI线程中的Handler + */ + private Handler mUIHandler; + + private Semaphore mSemaphorePoolThreadHandler = new Semaphore(0); + private Semaphore mSemaphoreThreadPool; + + private boolean isDiskCacheEnable = true; + + private static final String TAG = "ImageLoader"; + + public enum Type + { + FIFO, LIFO + } + + private ImageLoader(int threadCount, Type type) + { + init(threadCount, type); + } + + /** + * 初始化 + * + * @param threadCount + * @param type + */ + private void init(int threadCount, Type type) + { + initBackThread(); + + // 获取我们应用的最大可用内存 + int maxMemory = (int) Runtime.getRuntime().maxMemory(); + int cacheMemory = maxMemory / 8; + mLruCache = new LruCache(cacheMemory) + { + @Override + protected int sizeOf(String key, Bitmap value) + { + return value.getRowBytes() * value.getHeight(); + } + + }; + + // 创建线程池 + mThreadPool = Executors.newFixedThreadPool(threadCount); + mTaskQueue = new LinkedList(); + mType = type; + mSemaphoreThreadPool = new Semaphore(threadCount); + } + + /** + * 初始化后台轮询线程 + */ + private void initBackThread() + { + // 后台轮询线程 + mPoolThread = new Thread() + { + @Override + public void run() + { + Looper.prepare(); + mPoolThreadHandler = new Handler() + { + @Override + public void handleMessage(Message msg) + { + // 线程池去取出一个任务进行执行 + mThreadPool.execute(getTask()); + try + { + mSemaphoreThreadPool.acquire(); + } catch (InterruptedException e) + { + } + } + }; + // 释放一个信号量 + mSemaphorePoolThreadHandler.release(); + Looper.loop(); + } + }; + + mPoolThread.start(); + } + + public static ImageLoader getInstance() + { + if (mInstance == null) + { + synchronized (ImageLoader.class) + { + if (mInstance == null) + { + mInstance = new ImageLoader(DEAFULT_THREAD_COUNT, Type.LIFO); + } + } + } + return mInstance; + } + + public static ImageLoader getInstance(int threadCount, Type type) + { + if (mInstance == null) + { + synchronized (ImageLoader.class) + { + if (mInstance == null) + { + mInstance = new ImageLoader(threadCount, type); + } + } + } + return mInstance; + } + + /** + * 根据path为imageview设置图片 + * + * @param path + * @param imageView + */ + public void loadImage(final String path, final ImageView imageView, + final boolean isFromNet) + { + imageView.setTag(path); + if (mUIHandler == null) + { + mUIHandler = new Handler() + { + public void handleMessage(Message msg) + { + // 获取得到图片,为imageview回调设置图片 + ImgBeanHolder holder = (ImgBeanHolder) msg.obj; + Bitmap bm = holder.bitmap; + ImageView imageview = holder.imageView; + String path = holder.path; + // 将path与getTag存储路径进行比较 + if (imageview.getTag().toString().equals(path)) + { + imageview.setImageBitmap(bm); + } + } + }; + } + + + // 根据path在缓存中获取bitmap + Bitmap bm = getBitmapFromLruCache(path); + + if (bm != null) + { + refreashBitmap(path, imageView, bm); + } else + { + addTask(buildTask(path, imageView, isFromNet)); + } + + } + + /** + * 根据传入的参数,新建一个任务 + * + * @param path + * @param imageView + * @param isFromNet + * @return + */ + private Runnable buildTask(final String path, final ImageView imageView, + final boolean isFromNet) + { + return new Runnable() + { + @Override + public void run() + { + Bitmap bm = null; + if (isFromNet) + { + File file = getDiskCacheDir(imageView.getContext(), + md5(path)); + if (file.exists())// 如果在缓存文件中发现 + { + Log.e(TAG, "find image :" + path + " in disk cache ."); + bm = loadImageFromLocal(file.getAbsolutePath(), + imageView); + } else + { + if (isDiskCacheEnable)// 检测是否开启硬盘缓存 + { + boolean downloadState = DownloadImgUtils + .downloadImgByUrl(path, file); + if (downloadState)// 如果下载成功 + { + Log.e(TAG, + "download image :" + path + + " to disk cache . path is " + + file.getAbsolutePath()); + bm = loadImageFromLocal(file.getAbsolutePath(), + imageView); + } + } else + // 直接从网络加载 + { + Log.e(TAG, "load image :" + path + " to memory."); + bm = DownloadImgUtils.downloadImgByUrl(path, + imageView); + } + } + } else + { + bm = loadImageFromLocal(path, imageView); + } + // 3、把图片加入到缓存 + addBitmapToLruCache(path, bm); + refreashBitmap(path, imageView, bm); + mSemaphoreThreadPool.release(); + } + + + }; + } + + private Bitmap loadImageFromLocal(final String path, + final ImageView imageView) + { + Bitmap bm; + // 加载图片 + // 图片的压缩 + // 1、获得图片需要显示的大小 + ImageSizeUtil.ImageSize imageSize = ImageSizeUtil.getImageViewSize(imageView); + // 2、压缩图片 + bm = decodeSampledBitmapFromPath(path, imageSize.width, + imageSize.height); + return bm; + } + + /** + * 从任务队列取出一个方法 + * + * @return + */ + private Runnable getTask() + { + if (mType == Type.FIFO) + { + return mTaskQueue.removeFirst(); + } else if (mType == Type.LIFO) + { + return mTaskQueue.removeLast(); + } + return null; + } + + /** + * 利用签名辅助类,将字符串字节数组 + * + * @param str + * @return + */ + public String md5(String str) + { + byte[] digest = null; + try + { + MessageDigest md = MessageDigest.getInstance("md5"); + digest = md.digest(str.getBytes()); + return bytes2hex02(digest); + + } catch (NoSuchAlgorithmException e) + { + e.printStackTrace(); + } + return null; + } + + /** + * 方式二 + * + * @param bytes + * @return + */ + public String bytes2hex02(byte[] bytes) + { + StringBuilder sb = new StringBuilder(); + String tmp = null; + for (byte b : bytes) + { + // 将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制 + tmp = Integer.toHexString(0xFF & b); + if (tmp.length() == 1)// 每个字节8为,转为16进制标志,2个16进制位 + { + tmp = "0" + tmp; + } + sb.append(tmp); + } + + return sb.toString(); + + } + + private void refreashBitmap(final String path, final ImageView imageView, + Bitmap bm) + { + Message message = Message.obtain(); + ImgBeanHolder holder = new ImgBeanHolder(); + holder.bitmap = bm; + holder.path = path; + holder.imageView = imageView; + message.obj = holder; + mUIHandler.sendMessage(message); + } + + /** + * 将图片加入LruCache + * + * @param path + * @param bm + */ + protected void addBitmapToLruCache(String path, Bitmap bm) + { + if (getBitmapFromLruCache(path) == null) + { + if (bm != null) + mLruCache.put(path, bm); + } + } + + /** + * 根据图片需要显示的宽和高对图片进行压缩 + * + * @param path + * @param width + * @param height + * @return + */ + protected Bitmap decodeSampledBitmapFromPath(String path, int width, + int height) + { + // 获得图片的宽和高,并不把图片加载到内存中 + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + BitmapFactory.decodeFile(path, options); + + options.inSampleSize = ImageSizeUtil.caculateInSampleSize(options, + width, height); + + // 使用获得到的InSampleSize再次解析图片 + options.inJustDecodeBounds = false; + Bitmap bitmap = BitmapFactory.decodeFile(path, options); + return bitmap; + } + + private synchronized void addTask(Runnable runnable) + { + mTaskQueue.add(runnable); + // if(mPoolThreadHandler==null)wait(); + try + { + if (mPoolThreadHandler == null) + mSemaphorePoolThreadHandler.acquire(); + } catch (InterruptedException e) + { + } + mPoolThreadHandler.sendEmptyMessage(0x110); + } + + /** + * 获得缓存图片的地址 + * + * @param context + * @param uniqueName + * @return + */ + public File getDiskCacheDir(Context context, String uniqueName) + { + String cachePath; + if (Environment.MEDIA_MOUNTED.equals(Environment + .getExternalStorageState())) + { + cachePath = context.getExternalCacheDir().getPath(); + } else + { + cachePath = context.getCacheDir().getPath(); + } + return new File(cachePath + File.separator + uniqueName); + } + + /** + * 根据path在缓存中获取bitmap + * + * @param key + * @return + */ + private Bitmap getBitmapFromLruCache(String key) + { + return mLruCache.get(key); + } + + private class ImgBeanHolder + { + Bitmap bitmap; + ImageView imageView; + String path; + } +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageSizeUtil.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageSizeUtil.java new file mode 100644 index 0000000..96d642c --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageSizeUtil.java @@ -0,0 +1,131 @@ +package com.kejiang.yuandl.utils; + +import android.graphics.BitmapFactory.Options; +import android.util.DisplayMetrics; +import android.view.ViewGroup.LayoutParams; +import android.widget.ImageView; + +import java.lang.reflect.Field; + +/** + * http://blog.csdn.net/lmj623565791/article/details/41874561 + * @author zhy + * + */ +public class ImageSizeUtil +{ + /** + * 根据需求的宽和高以及图片实际的宽和高计算SampleSize + * + * @param options + * @param width + * @param height + * @return + */ + public static int caculateInSampleSize(Options options, int reqWidth, + int reqHeight) + { + int width = options.outWidth; + int height = options.outHeight; + + int inSampleSize = 1; + + if (width > reqWidth || height > reqHeight) + { + int widthRadio = Math.round(width * 1.0f / reqWidth); + int heightRadio = Math.round(height * 1.0f / reqHeight); + + inSampleSize = Math.max(widthRadio, heightRadio); + } + + return inSampleSize; + } + + /** + * 根据ImageView获适当的压缩的宽和高 + * + * @param imageView + * @return + */ + public static ImageSize getImageViewSize(ImageView imageView) + { + + ImageSize imageSize = new ImageSize(); + DisplayMetrics displayMetrics = imageView.getContext().getResources() + .getDisplayMetrics(); + + + LayoutParams lp = imageView.getLayoutParams(); + + int width = imageView.getWidth();// 获取imageview的实际宽度 + if (width <= 0) + {if(lp!=null){ + width = lp.width;// 获取imageview在layout中声明的宽度 + } + + } + if (width <= 0) + { + //width = imageView.getMaxWidth();// 检查最大值 + width = getImageViewFieldValue(imageView, "mMaxWidth"); + } + if (width <= 0) + { + width = displayMetrics.widthPixels; + } + + int height = imageView.getHeight();// 获取imageview的实际高度 + if (height <= 0) + {if(lp!=null){ + height = lp.height;// 获取imageview在layout中声明的宽度 + } + + } + if (height <= 0) + { + height = getImageViewFieldValue(imageView, "mMaxHeight");// 检查最大值 + } + if (height <= 0) + { + height = displayMetrics.heightPixels; + } + imageSize.width = width; + imageSize.height = height; + + return imageSize; + } + + public static class ImageSize + { + public int width; + public int height; + } + + /** + * 通过反射获取imageview的某个属性值 + * + * @param object + * @param fieldName + * @return + */ + private static int getImageViewFieldValue(Object object, String fieldName) + { + int value = 0; + try + { + Field field = ImageView.class.getDeclaredField(fieldName); + field.setAccessible(true); + int fieldValue = field.getInt(object); + if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) + { + value = fieldValue; + } + } catch (Exception e) + { + } + return value; + + } + + +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageUtils.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageUtils.java new file mode 100644 index 0000000..5492458 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/ImageUtils.java @@ -0,0 +1,87 @@ +package com.kejiang.yuandl.utils; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Matrix; +import android.media.ExifInterface; +import android.view.Display; +import android.view.WindowManager; + +import java.io.IOException; + +/** + * 图像相关工具类 + * Created by yuandl on 2016/3/26 0026. + */ +public class ImageUtils { + /** + * 读取照片exif信息中的旋转角度 + * + * @param path 照片路径 + * @return角度 + */ + + public static int readPictureDegree(String path) { + int degree = 0; + try { + ExifInterface exifInterface = new ExifInterface(path); + int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); + switch (orientation) { + case ExifInterface.ORIENTATION_ROTATE_90: + degree = 90; + break; + case ExifInterface.ORIENTATION_ROTATE_180: + degree = 180; + break; + case ExifInterface.ORIENTATION_ROTATE_270: + degree = 270; + break; + } + } catch (IOException e) { + e.printStackTrace(); + } + return degree; + } + + /** + * 将图片旋转90度 + * + * @param img + * @return + */ + public static Bitmap toturn(Bitmap img) { + Matrix matrix = new Matrix(); + matrix.postRotate(+90); /*翻转90度*/ + int width = img.getWidth(); + int height = img.getHeight(); + img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true); + return img; + } + public static Bitmap getScaleBitmap(Context ctx, String filePath) { + BitmapFactory.Options opt = new BitmapFactory.Options(); + opt.inJustDecodeBounds = true; + Bitmap bmp = BitmapFactory.decodeFile(filePath, opt); + + int bmpWidth = opt.outWidth; + int bmpHeght = opt.outHeight; + + WindowManager windowManager = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); + Display display = windowManager.getDefaultDisplay(); + int screenWidth = display.getWidth(); + int screenHeight = display.getHeight(); + + opt.inSampleSize = 1; + if (bmpWidth > bmpHeght) { + if (bmpWidth > screenWidth) + opt.inSampleSize = bmpWidth / screenWidth; + } else { + if (bmpHeght > screenHeight) + opt.inSampleSize = bmpHeght / screenHeight; + } + opt.inJustDecodeBounds = false; + + bmp = BitmapFactory.decodeFile(filePath, opt); + return bmp; + } +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/SharedPreferencesUtils.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/SharedPreferencesUtils.java new file mode 100644 index 0000000..3184510 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/SharedPreferencesUtils.java @@ -0,0 +1,121 @@ +package com.kejiang.yuandl.utils; + +import android.content.Context; +import android.content.SharedPreferences; + +import com.orhanobut.logger.Logger; + +/** + * SharedPreferences的一个工具类,调用setParam就能保存String, Integer, Boolean, Float, + * Long类型的参数 同样调用getParam就能获取到保存在手机里面的数据 + * + * @author xiaanming + */ +public class SharedPreferencesUtils { + private Context context; + /** + * 保存在手机里面的文件名 + */ + private String FILE_NAME = "share_date"; + + // public static SharedPreferencesUtils getInstens(String fileName) { + // FILE_NAME = fileName; + // if (sharedPreferencesUtils == null) { + // synchronized (SharedPreferencesUtils.class) { + // if (sharedPreferencesUtils == null) { + // sharedPreferencesUtils = new SharedPreferencesUtils(); + // } + // } + // } + // return sharedPreferencesUtils; + // } + + public SharedPreferencesUtils(String FILE_NAME) { + this.FILE_NAME = FILE_NAME; + + } + public SharedPreferencesUtils(Context context) { + this.context=context; + + } + /** + * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 + * + * @param context + * @param key + * @param object + */ + public void setParam(String key, Object object) { + + String type = object.getClass().getSimpleName(); + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sp.edit(); + if ("String".equals(type)) { + editor.putString(key, object.toString()); + } else if ("Integer".equals(type)) { + editor.putInt(key, (Integer) object); + } else if ("Boolean".equals(type)) { + editor.putBoolean(key, (Boolean) object); + } else if ("Float".equals(type)) { + editor.putFloat(key, (Float) object); + } else if ("Long".equals(type)) { + editor.putLong(key, (Long) object); + } + + editor.commit(); + } + + /** + * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 + * + * @param context + * @param key + * @param defaultObject + * @return + */ + public Object getParam(String key, Object defaultObject) { + String type = defaultObject.getClass().getSimpleName(); + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + + if ("String".equals(type)) { + return sp.getString(key, (String) defaultObject); + } else if ("Integer".equals(type)) { + return sp.getInt(key, (Integer) defaultObject); + } else if ("Boolean".equals(type)) { + return sp.getBoolean(key, (Boolean) defaultObject); + } else if ("Float".equals(type)) { + return sp.getFloat(key, (Float) defaultObject); + } else if ("Long".equals(type)) { + return sp.getLong(key, (Long) defaultObject); + } + + return null; + } + + /** + * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 + * + * @param context + * @param key + * @return + */ + // Delete + public void remove( String key) { + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sp.edit(); + editor.remove(key); + editor.commit(); + } + + public void clear() { + SharedPreferences sp = context.getSharedPreferences(FILE_NAME, + Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sp.edit(); + editor.clear(); + editor.commit(); + Logger.e("clear>FILE_NAME=" + FILE_NAME); + } +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/Tools.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/Tools.java new file mode 100644 index 0000000..faef487 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/utils/Tools.java @@ -0,0 +1,1270 @@ +package com.kejiang.yuandl.utils; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.ContentResolver; +import android.content.Context; +import android.content.pm.PackageManager.NameNotFoundException; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.Bitmap.Config; +import android.graphics.Canvas; +import android.graphics.Matrix; +import android.graphics.Paint; +import android.graphics.PorterDuff.Mode; +import android.graphics.PorterDuffXfermode; +import android.graphics.Rect; +import android.graphics.RectF; +import android.net.Uri; +import android.os.Environment; +import android.text.Html; +import android.text.Spanned; +import android.text.format.DateFormat; +import android.util.DisplayMetrics; +import android.util.Log; +import android.view.View; +import android.view.WindowManager; +import android.view.animation.Animation; +import android.view.animation.AnimationSet; +import android.view.animation.ScaleAnimation; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.Toast; + +import com.orhanobut.logger.Logger; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author TangWei 2013-10-24上午10:38:01 + */ +public class Tools { + + /** + * TODO<取得日期是某年的第几周> + * + * @param date + * @return + * @throw [url=home.php?mod=space&uid=7300]@return[/url] int + */ + @SuppressLint("SimpleDateFormat") + public static int getWeekOfYear(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int week_of_year = cal.get(Calendar.WEEK_OF_YEAR); + return week_of_year; + } + + /** + * 压缩图片 + * + * @param bm + * @param newWidth + * @param newHeight + * @return + */ + public static Bitmap scaleImg(Bitmap bm, int newWidth, int newHeight) { + // 获得图片的宽高 + int width = bm.getWidth(); + int height = bm.getHeight(); + // 设置想要的大小 + int newWidth1 = newWidth; + int newHeight1 = newHeight; + // 计算缩放比例 + float scaleWidth = ((float) newWidth1) / width; + float scaleHeight = ((float) newHeight1) / height; + // 取得想要缩放的matrix参数 + Matrix matrix = new Matrix(); + matrix.postScale(scaleWidth, scaleHeight); + matrix.postRotate(0); + + return Bitmap.createScaledBitmap(bm, newWidth, newHeight, false); + } + + public static void Log(String s) { + if (s == null) { + s = "传进来的是null"; + } + + Log.i("logs", s); + } + + public static String MapGetString(Map map, String key) { + if (map.containsKey(key)) { + if (map.get(key) != null && !"".equals(map.get(key))) { + return ((String) map.get(key)).trim(); + } else { + return ""; + } + } else { + return ""; + } + } + + public static String ListToString(@SuppressWarnings("rawtypes") List list) { + String s = Pattern + .compile("\\b([\\w\\W])\\b") + .matcher( + list.toString().substring(1, + list.toString().length() - 1)).replaceAll("$1") + .replaceAll(",", " "); + return s; + + } + + public static Spanned setErrorTextBlack(String s) { + return Html.fromHtml("" + s + ""); + + } + + public static void Toast(Context context, String s) { + // if (context == null) + // context = ShiQiangApplication.getInstance().getApplicationContext(); + if (s != null) { + Toast.makeText(context, s, + Toast.LENGTH_SHORT).show(); + } + } + + public static void Toast(Context context, int res) { + if (context != null) { + Toast(context, context.getString(res)); + } + } + + // 得到versionName + public static String getVerName(Context context) { + String verName = ""; + try { + verName = context.getPackageManager().getPackageInfo( + context.getPackageName(), 0).versionName; + } catch (NameNotFoundException e) { + e.printStackTrace(); + } + return verName; + + } + + public static String millisToString(long millis) { + boolean negative = millis < 0; + millis = Math.abs(millis); + + millis /= 1000; + int sec = (int) (millis % 60); + millis /= 60; + int min = (int) (millis % 60); + millis /= 60; + int hours = (int) millis; + + String time; + DecimalFormat format = (DecimalFormat) NumberFormat + .getInstance(Locale.US); + format.applyPattern("00"); + if (millis > 0) { + time = (negative ? "-" : "") + + (hours == 0 ? 00 : hours < 10 ? "0" + hours : hours) + + ":" + (min == 0 ? 00 : min < 10 ? "0" + min : min) + ":" + + (sec == 0 ? 00 : sec < 10 ? "0" + sec : sec); + } else { + time = (negative ? "-" : "") + min + ":" + format.format(sec); + } + return time; + } + + // 得到versionName + public static int getVerCode(Context context) { + int verCode = 0; + try { + verCode = context.getPackageManager().getPackageInfo( + context.getPackageName(), 0).versionCode; + } catch (NameNotFoundException e) { + e.printStackTrace(); + } + return verCode; + + } + + /** + * 判断 多个字段的值否为空 + * + * @return true为null或空; false不null或空 + * @author Michael.Zhang 2013-08-02 13:34:43 + */ + public static boolean isNull(String... ss) { + for (int i = 0; i < ss.length; i++) { + if (null == ss[i] || ss[i].equals("") + || ss[i].equalsIgnoreCase("null")) { + return true; + } + } + + return false; + } + + /** + * 判断 一个字段的值否为空 + * + * @param s + * @return + * @author Michael.Zhang 2013-9-7 下午4:39:00 + */ + public static boolean isNull(String s) { + return null == s || s.equals("") || s.equalsIgnoreCase("null"); + + } +/** + * 判断 一个字段的值否为空 + * + * @param s + * @return + * @author Michael.Zhang 2013-9-7 下午4:39:00 + */ + public static boolean isNull2(String s) { + return null == s || s.equals(""); + + } + + /** + * 判断 一个集合的值否为空 + * + * @return true为null或空; false不null或空 + * @author Michael.Zhang 2013-08-02 13:34:43 + */ + public static boolean isNull(List list) { + for (int i = 0; i < list.size(); i++) { + if (null == list.get(i) || Tools.isNull(list.get(i))) { + return true; + } + } + + return false; + } + + /** + * 判断 多个字段的值否为空 + * + * @return true为null或空; false不null或空 + * @author Michael.Zhang 2013-08-02 13:34:43 + */ + public static boolean isNull(TextView... vv) { + for (int i = 0; i < vv.length; i++) { + if (null == vv[i] || Tools.isNull(Tools.getText(vv[i]))) { + return true; + } + } + + return false; + } + + /** + * 判断 一个字段的值否为空 + * + * @param v + * @return + * @author Michael.Zhang 2013-9-7 下午4:39:00 + */ + public static boolean isNull(TextView v) { + return null == v || Tools.isNull(Tools.getText(v)); + + } + + /** + * 判断 一个字段的值否为空 + * + * @param v + * @return + * @author Michael.Zhang 2013-9-7 下午4:39:00 + */ + public static boolean isNull(EditText v) { + return null == v || Tools.isNull(Tools.getText(v)); + + } + + /** + * 判断两个字段是否一样 + * + * @author Michael.Zhang 2013-08-02 13:32:51 + */ + public static boolean judgeStringEquals(String s0, String s1) { + return s0 != null && s0.equals(s1); + } + + /** + * 将dp类型的尺寸转换成px类型的尺寸 + * + * @param size + * @param context + * @return + */ + public static int DPtoPX(int size, Context context) { + DisplayMetrics metrics = new DisplayMetrics(); + ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)) + .getDefaultDisplay().getMetrics(metrics); + return (int) ((float) size * metrics.density + 0.5); + } + + /** + * 屏幕宽高 + * + * @param context + * @return 0:width,1:height + * @author TangWei 2013-11-5上午10:27:54 + */ + public static int[] ScreenSize(Context context) { + DisplayMetrics metrics = new DisplayMetrics(); + ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)) + .getDefaultDisplay().getMetrics(metrics); + return new int[]{metrics.widthPixels, metrics.heightPixels}; + } + + /** + * double 整理 + * + * @return + */ + public static Double roundDouble(double val, int scale) { + if (scale < 0) { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b = ((0 == val) ? new BigDecimal("0.0") : new BigDecimal( + Double.toString(val))); + BigDecimal one = new BigDecimal("1"); + return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + /** + * 判断 列表是否为空 + * + * @return true为null或空; false不null或空 + */ + @SuppressWarnings("rawtypes") + public static boolean isEmptyList(List list) { + return list == null || list.size() == 0; + } + + /** + * 判断 列表是否为空 + * + * @return true为null或空; false不null或空 + */ + @SuppressWarnings("rawtypes") + public static boolean isEmptyList(List... list) { + for (int i = 0; i < list.length; i++) { + if (isEmptyList(list[i])) { + return true; + } + } + + return false; + } + + /** + * 判断 列表是否为空 + * + * @return true为null或空; false不null或空 + */ + public static boolean isEmptyList(Object[] list) { + return list == null || list.length == 0; + } + + /** + * 判断 列表是否为空 + * + * @return true为null或空; false不null或空 + */ + public static boolean isEmptyList(Object[]... list) { + for (int i = 0; i < list.length; i++) { + if (isEmptyList(list[i])) { + return true; + } + } + + return false; + } + + /** + * 判断sd卡是否存在 + * + * @return + * @author Michael.Zhang 2013-07-04 11:30:54 + */ + public static boolean judgeSDCard() { + String status = Environment.getExternalStorageState(); + return status.equals(Environment.MEDIA_MOUNTED); + } + + /** + * 判断 http 链接 + * + * @param url + * @return + * @author Michael.Zhang + */ + public static boolean isUrl(String url) { + return url != null && url.startsWith("http://"); + } + + /** + * 获取保存到View的Tag中的字符串 + * + * @param v + * @return + */ + public static String getTagString(View v) { + try { + return v.getTag().toString(); + } catch (Exception e) { + return ""; + } + } + + /** + * 获取文本控件上显示的文字 + * + * @param tv + * @return + * @author TangWei 2013-9-29下午2:40:52 + */ + public static String getText(TextView tv) { + if (tv != null) + return tv.getText().toString().trim(); + return ""; + } + + /** + * 获取文本控件上显示的文字 + * + * @param tv + * @return + * @author TangWei 2013-9-29下午2:40:52 + */ + public static String getText(EditText tv) { + if (tv != null) + return tv.getText().toString().trim(); + return ""; + } + + /** + * 隐藏键盘 + * + * @author TangWei 2013-9-13下午7:51:32 + */ + public static void hideKeyboard(Activity activity) { + ((InputMethodManager) activity + .getSystemService(Context.INPUT_METHOD_SERVICE)) + .hideSoftInputFromWindow(activity.getCurrentFocus() + .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); + } + + // public static void playSound(int raw, Context context) { + // SoundPool sp; + // sp = new SoundPool(1000, AudioManager.STREAM_SYSTEM, 5); + // int task = sp.load(context, raw, 1); + // sp.play(task, 1, 1, 0, 0, 1); + // } + + /** + * 显示纯汉字的星期名称 + * + * @param i 星期:1,2,3,4,5,6,7 + * @return + * @author TangWei 2013-10-25上午11:31:51 + */ + public static String changeWeekToHanzi(int i) { + switch (i) { + case 1: + return "星期一"; + case 2: + return "星期二"; + case 3: + return "星期三"; + case 4: + return "星期四"; + case 5: + return "星期五"; + case 6: + return "星期六"; + case 7: + return "星期日"; + default: + return ""; + } + } + + /** + * 验证身份证号码 + * + * @param idCard + * @return + * @author TangWei + */ + public static boolean validateIdCard(String idCard) { + if (isNull(idCard)) + return false; + String pattern = "^[0-9]{17}[0-9|xX]{1}$"; + return idCard.matches(pattern); + } + + /** + * 验证推荐人编码 + * + * @param code + * @return + * @author TangWei + */ + public static boolean validateCode(String code) { + if (isNull(code)) + return false; + String pattern = "^\\d{6}$"; + return code.matches(pattern); + } /** + * 验证推荐人编码 + * + * @param lelephone + * @return 区号-号码 ------------------- + String regex1 = "\\(?(010|021|022|023|024|025|026|027|028|029|852)?\\)?-?\\d{8}";//3位区号,8位号码 + String regex2 = "\\(?(0[3-9][0-9]{2})?\\)?-?\\d{7,8}";//4位区号 + String regex3 = "(\\(?(010|021|022|023|024|025|026|027|028|029|852)?\\)?-?\\d{8})|(\\(?(0[3-9][0-9]{2})?\\)?-?\\d{7,8})"; + * @author TangWei + */ + public static boolean validateTelePhone(String lelephone) { + if (isNull(lelephone)) + return false; + String pattern = "^(\\d{11})$|^(\\d{3,5}[-]?\\d{6,8})$"; + return lelephone.matches(pattern); + } + + /** + * 验证手机号码 + * + * @param phone + * @return + * @author TangWei + */ + public static boolean validatePhone(String phone) { + if (isNull(phone)) + return false; + String pattern = "^1[3,4,5,6,7,8]+\\d{9}$"; + return phone.matches(pattern); + } + + /** + * 验证微信号 + * + * @param wx + * @return + * @author TangWei + */ + public static boolean validateWX(String wx) { + if (isNull(wx)) + return false; + String pattern = "^[a-zA-Z\\d_]+$"; + return wx.matches(pattern); + } + + /** + * 验证中文名 + * + * @param name + * @return + * @author TangWei + */ + public static boolean validateName(String name) { + if (isNull(name)) + return false; + String pattern = "[\\u4E00-\\u9FA5]{2,4}"; + return name.matches(pattern); + } + + public static boolean isContainsChinese(String str) { + if (isNull(str)) + return false; + String regEx = "[\u4e00-\u9fa5]"; + Pattern pat = Pattern.compile(regEx); + Matcher matcher = pat.matcher(str); + boolean flg = false; + if (matcher.find()) { + flg = true; + } + return flg; + } + + public static boolean validatePassWord(String password) { + if (isContainsChinese(password)) { + return false; + } else { + return password.trim().length() >= 6 && password.trim().length() <= 16; + } + + } + + /** + * 简单的验证一下银行卡号 + * + * @param bankCard 信用卡是16位,其他的是13-19位 + * @return + */ + public static boolean validateBankCard(String bankCard) { + if (isNull(bankCard)) + return false; + String pattern = "^\\d{13,19}$"; + return bankCard.matches(pattern); + } + + /** + * 验证邮箱 + * + * @param email + * @return + * @author TangWei 2013-12-13下午2:33:16 + */ + public static boolean validateEmail(String email) { + if (isNull(email)) + return false; + String pattern = "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$"; + return email.matches(pattern); + } + + public static boolean isEmail(String email) { + String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; + Pattern p = Pattern.compile(str); + Matcher m = p.matcher(email); + + return m.matches(); + } + + // public static boolean validateArtBeianAnName(String email) { +// String str = "/\\s+|^c:\\\\con\\\\con|[%,\\*\\\"\\s\\<\\>\\&]|\\xA1\\xA1|\\xAC\\xA3|^Guest|^\\xD3\\xCE\\xBF\\xCD|\\xB9\\x43\\xAB\\xC8/is"; +// Pattern p = Pattern.compile(str); +// Matcher m = p.matcher(email); +// +// return m.matches(); +// } + public static boolean validateArtBeianAnEmail(String email) { + String str = "/^([a-z0-9\\-_.+]+)@([a-z0-9\\-]+[.][a-z0-9\\-.]+)$/"; + Pattern p = Pattern.compile(str); + Matcher m = p.matcher(email); + + return m.matches(); + } + + public static String trimString(String str) { + if (!Tools.isNull(str)) { + return str.trim(); + } + return ""; + } + + public static int StringToInt(String str) { + try { + return Integer.parseInt(str); + } catch (Exception e) { + return 0; + } + } + + public static float StringToFloat(String str) { + try { + return Float.parseFloat(str); + } catch (Exception e) { + return 0.00f; + } + } + + public static String formatString(Object obj) { + try { + if (!Tools.isNull(obj.toString())) { + return obj.toString(); + } else { + return ""; + } + } catch (Exception e) { + return ""; + } + } + + /** + * 格式化money,当返回数据为空时,返回0.00 + * + * @param obj + * @return + * @author TangWei 2013-11-23上午11:42:33 + */ + public static String formatMoney(Object obj) { + String money = formatString(obj); + if (money.length() == 0) { + money = "0.00"; + } + return money; + } + + /** + * 计算某天后的多少天 + * + * @param startDay + * @param days + * @return + */ + public static Date calculateDate(Date startDay, int days) { + Calendar cal = Calendar.getInstance(); + cal.setTime(startDay); + cal.add(Calendar.DAY_OF_YEAR, days); + return cal.getTime(); + } + + /** + * 格式化日期,针对于传过来的日期是毫秒数 + * + * @param date 日期毫秒数 + * @param format 格式化样式 示例:yyyy-MM-dd HH:mm:ss + * @return + * @author TangWei 2013-11-29上午11:31:49 + */ + @SuppressLint("SimpleDateFormat") + public static String formatDate(Object date, String format) { + try { + return new SimpleDateFormat(format).format(new Date(Long + .parseLong(formatString(date)) * 1000)); + } catch (Exception e) { + return ""; + } + } + + /** + * 格式化日期,针对于传过来的日期是毫秒数
+ * 转换样式:2013-11-12 11:12:13 + * + * @param date 日期毫秒数 + * @return + * @author TangWei 2013-11-22上午11:38:13 + */ + public static String formatTime(Object date) { + return formatDate(date, "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 格式化日期,针对于传过来的日期是毫秒数
+ * 转换样式:2013-11-12 11:12:13 + * + * @param date 日期毫秒数 + * @return + * @author TangWei 2013-11-22上午11:38:13 + */ + @SuppressLint("SimpleDateFormat") + public static String formatAddTime(String date) { + SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm"); + + try { + return sdf.format((sdf.parse(date))); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return date; + } + + /** + * 格式化日期,针对于传过来的日期是毫秒数
+ * 转换样式:2013-11-12 + * + * @param date 日期毫秒数 + * @return + * @author TangWei 2013-11-22上午11:38:13 + */ + public static String formatDate(Object date) { + return formatDate(date, "yyyy-MM-dd"); + } + + public static String getFormatedYear(long longTime) { + return DateFormat.format("yy-MM-dd HH:mm", longTime * 1000).toString(); + } + public static String getFormatedNotYear(long longTime) { + return DateFormat.format("MM-dd", longTime * 1000).toString(); + } + + public static String getFormatedDate(long longTime) { + return DateFormat.format("MM月dd日", longTime * 1000).toString(); + } + + public static String getOrderDate(long longTime) { + return DateFormat.format("yyyyMMddHHmmss", longTime).toString(); + } + + public static String getFormatedTime(long longTime) { + return DateFormat.format("kk:mm", longTime * 1000).toString(); + } + + public static String getFormatedMiao(long longTime) { + return DateFormat.format("kk:mm:ss", longTime * 1000).toString(); + } + + /** + * 获取屏幕像素尺寸 + * + * @return 数组:0-宽,1-高 + * @author TangWei 2013-10-31下午1:08:22 + */ + public static int[] getScreenSize(Context context) { + int[] size = new int[2]; + DisplayMetrics metrics = new DisplayMetrics(); + ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)) + .getDefaultDisplay().getMetrics(metrics); + size[0] = metrics.widthPixels; + size[1] = metrics.heightPixels; + return size; + } + + public static String formatMoney(String money) { + if (money.contains(".")) { + String[] ss = money.split("\\."); + Logger.d( Arrays.toString(ss)); + if (ss[1].length() == 0) { + return ss[0] + ".00"; + } else if (ss[1].length() == 1) { + return ss[0] +"."+ ss[1] + "0"; + } else if (ss[1].length() == 2) { + return money; + } else { + return money; + } + } else { + return money + ".00"; + + } + } + + /** + * 设置圆角的图片 + * + * @param bitmap 图片 + * @param pixels 角度 + * @return + * @author TangWei 2013-12-10下午4:43:33 + */ + public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) { + try { + if (bitmap != null) { + Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), + bitmap.getHeight(), Config.ARGB_8888); + Canvas canvas = new Canvas(output); + + final int color = 0xff424242; + final Paint paint = new Paint(); + final Rect rect = new Rect(0, 0, bitmap.getWidth(), + bitmap.getHeight()); + final RectF rectF = new RectF(rect); + final float roundPx = pixels; + + paint.setAntiAlias(true); + canvas.drawARGB(0, 0, 0, 0); + paint.setColor(color); + canvas.drawRoundRect(rectF, roundPx, roundPx, paint); + + paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); + canvas.drawBitmap(bitmap, rect, rect, paint); + + return output; + } + } catch (Exception e) { + } + + return bitmap; + } + + /** + * 将图片转换为圆形的 + * + * @param bitmap + * @return + * @author TangWei 2013-12-10下午4:45:47 + */ + public static Bitmap toRoundBitmap(Bitmap bitmap) { + if (bitmap != null) { + bitmap = cutSquareBitmap(bitmap); + return toRoundCorner(bitmap, bitmap.getWidth() / 2); + } + return bitmap; + } + + /** + * 把图片切成正方形的 + * + * @param bitmap + * @return + * @author TangWei 2013-12-10下午5:16:18 + */ + public static Bitmap cutSquareBitmap(Bitmap bitmap) { + try { + if (bitmap != null) { + Bitmap result; + int w = bitmap.getWidth();// 输入长方形宽 + int h = bitmap.getHeight();// 输入长方形高 + int nw;// 输出正方形宽 + if (w > h) { + // 宽大于高 + nw = h; + result = Bitmap.createBitmap(bitmap, (w - nw) / 2, 0, nw, + nw); + } else { + // 高大于宽 + nw = w; + result = Bitmap.createBitmap(bitmap, 0, (h - nw) / 2, nw, + nw); + } + return result; + } + } catch (Exception e) { + } + return bitmap; + } + + /** + * 获取在GridView中一行中一张正方形图片的尺寸大小 + * + * @param context 上下文,用于计算屏幕的宽度 + * @param offset 界面上左右两边的偏移量,dp值 + * @param spac 水平方向,图片之间的间距,dp值 + * @param count 一行中图片的个数 + * @return + * @author TangWei 2013-12-12下午1:15:49 + */ + public static int getImageSize(Context context, int offset, int spac, + int count) { + int width = getScreenSize(context)[0] - Tools.DPtoPX(offset, context) + - (Tools.DPtoPX(spac, context) * (count - 1)); + return width / count; + } + + /** + * 获取一个圆弧上等分点的坐标列表 + * + * @param radius 半径 + * @param count 等分点个数 + * @param start_angle 开始角度 + * @param end_angle 结束角度 + * @return + * @author TangWei 2013-12-16下午5:06:31 + */ + public static ArrayList getDividePoints(double radius, int count, + double start_angle, double end_angle) { + ArrayList list = new ArrayList(); + double sub_angle = (start_angle - end_angle) / ((double) (count - 1)); + for (int i = 0; i < count; i++) { + double angle = (start_angle - sub_angle * i) * Math.PI / 180; + double x = radius * Math.cos(angle); + double y = radius * Math.sin(angle); + list.add(new String[]{x + "", y + ""}); + } + return list; + } + + /** + * 判断字符串是邮箱还是手机号码 + * + * @param str + * @return 1-手机号码,2-邮箱,如果都不是则返回0 + * @author TangWei 2013-12-19下午1:59:16 + */ + public static int validatePhoneOrEmail(String str) { + if (validatePhone(str)) + return 1; + if (validateEmail(str)) + return 2; + return 0; + } + + /** + * 播放动画 + * + * @param layout + * @param img + * @param + * @param + */ + public static void startAnimation(final View layout, ImageView img, + int drawableBefore, int drawableClick, boolean isClicked) { + if (isClicked) { + img.setBackgroundResource(drawableClick); + } else { + img.setBackgroundResource(drawableBefore); + } + + // 播放动画 + AnimationSet animationSet = new AnimationSet(true); + ScaleAnimation scaleAnimation1 = new ScaleAnimation(1, 1.2f, 1, 1.2f, + Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, + 0.5f); + ScaleAnimation scaleAnimation2 = new ScaleAnimation(1.2f, 1, 1.2f, 1, + Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, + 0.5f); + scaleAnimation1.setStartOffset(0); + scaleAnimation1.setDuration(50); + scaleAnimation2.setStartOffset(50); + scaleAnimation2.setDuration(50); + animationSet.addAnimation(scaleAnimation1); + animationSet.addAnimation(scaleAnimation2); + animationSet.setFillAfter(true); + img.startAnimation(animationSet); + animationSet.setAnimationListener(new Animation.AnimationListener() { + @Override + public void onAnimationStart(Animation animation) { + layout.setEnabled(false); + } + + @Override + public void onAnimationEnd(Animation animation) { + layout.setEnabled(true); + } + + @Override + public void onAnimationRepeat(Animation animation) { + } + }); + } + + /** + * bitmap转为base64 + * + * @param bitmap + * @return + */ + public static String bitmapToBase64(Bitmap bitmap) { + + String result = null; + ByteArrayOutputStream baos = null; + try { + if (bitmap != null) { + baos = new ByteArrayOutputStream(); + bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); + + baos.flush(); + baos.close(); + + byte[] bitmapBytes = baos.toByteArray(); + result = Base64.encode(bitmapBytes); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (baos != null) { + baos.flush(); + baos.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + /** + * SD卡是否存在 + */ + public static boolean existSDCard() { + return Environment.getExternalStorageState().equals( + Environment.MEDIA_MOUNTED); + } + + /** + * 创建文件夹 + */ + public static void makeDir(String path) { + File rootFile = new File(path); + if (!rootFile.exists()) { + rootFile.mkdir(); + } + } + + /** + * 根据Uri返回文件路径 + * + * @param mUri + * @return String + * @author gdpancheng@gmail.com 2013-3-18 上午10:17:55 + */ + public static String getFilePath(ContentResolver mContentResolver, Uri mUri) { + try { + if (mUri.getScheme().equals("file")) { + return mUri.getPath(); + } else { + return getFilePathByUri(mContentResolver, mUri); + } + } catch (FileNotFoundException ex) { + return null; + } + } + + /** + * 将100以内的阿拉伯数字转换成中文汉字(15变成十五) + * + * @param round 最大值50 + * @return >99的,返回“” + */ + public static String getHanZi1(int round) { + if (round > 99 || round == 0) { + return ""; + } + int ge = round % 10; + int shi = (round - ge) / 10; + String value = ""; + if (shi != 0) { + if (shi == 1) { + value = "十"; + } else { + value = getHanZi2(shi) + "十"; + } + + } + value = value + getHanZi2(ge); + return value; + } + + /** + * 将0-9 转换为 汉字( _一二三四五六七八九) + * + * @param round + * @return + */ + public static String getHanZi2(int round) { + String[] value = {"", "一", "二", "三", "四", "五", "六", "七", "八", "九"}; + return value[round]; + } + + /** + * 将content: 开通的系统uri转换成绝对路径 + * + * @param mContentResolver + * @param mUri + * @return + * @throws FileNotFoundException + */ + public static String getFilePathByUri(ContentResolver mContentResolver, + Uri mUri) throws FileNotFoundException { + + String imgPath; + Cursor cursor = mContentResolver.query(mUri, null, null, null, null); + cursor.moveToFirst(); + imgPath = cursor.getString(1); // 图片文件路径 + return imgPath; + } + + /** + * 去除字符串中的 ":" + * + * @param str + * @return + */ + public static String deleteColon(String str) { + if (str == null) { + return null; + } else { + return str.replace(":", ""); + } + } + + /** + * 将 1800 加个":",变成 18:00 + * + * @param str + * @return + */ + public static String addColon(String str) { + if (str == null || str.length() != 4) { + return null; + } + return str.substring(0, 2) + ":" + str.substring(2, 4); + } + + /** + * 获取map中的值 + * + * @param + * @return + */ + public static String getValue(Map map, String key) { + if (map == null || map.size() == 0) { + return ""; + } else if (isNull(key)) { + return ""; + } else if (map.containsKey(key)) { + Object data = map.get(key); + if (data instanceof String) { + if (isNull2((String) map.get(key))) { + return ""; + } else { + return map.get(key).toString(); + } + } else { + return String.valueOf(map.get(key)); + } + + } else { + return ""; + } + } + + static Toast toast; + + public static void show(Context context, CharSequence message, int duration) { + if (null == toast) { + toast = Toast.makeText(context, message, duration); + // toast.setGravity(Gravity.CENTER, 0, 0); + } else { + toast.setText(message); + } + toast.show(); + } + //强制显示或者关闭系统键盘 + public static void KeyBoard(final EditText txtSearchKey,final String status) + { + + Timer timer = new Timer(); + timer.schedule(new TimerTask(){ + @Override + public void run() + { + InputMethodManager m = (InputMethodManager) + txtSearchKey.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if(status.equals("open")) + { + m.showSoftInput(txtSearchKey,InputMethodManager.SHOW_FORCED); + } + else + { + m.hideSoftInputFromWindow(txtSearchKey.getWindowToken(), 0); + } + } + }, 300); + } + //显示虚拟键盘 + public static void showKeyboard(View v) + { + InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE ); + + imm.showSoftInput(v,InputMethodManager.SHOW_FORCED); + + } +} diff --git a/libray_lxndroid/src/main/java/com/kejiang/yuandl/view/LoadingDialog.java b/libray_lxndroid/src/main/java/com/kejiang/yuandl/view/LoadingDialog.java new file mode 100644 index 0000000..d355c43 --- /dev/null +++ b/libray_lxndroid/src/main/java/com/kejiang/yuandl/view/LoadingDialog.java @@ -0,0 +1,60 @@ +package com.kejiang.yuandl.view; + +import android.app.Dialog; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.TextView; + +import com.kejiang.yuandl.R; + + +/** + * ToDo 进度加载对话框 + * Author: dylan + * Date: 2014-12-29 + * Time: 13:34 + */ +public class LoadingDialog { + private Dialog dialog; + private Context context; + private TextView tv_text; + + public LoadingDialog(Context context) { + this.context = context; + } + + public Dialog show(String message) { + View view = LayoutInflater.from(context).inflate(R.layout.loading, null); + tv_text = (TextView) view.findViewById(R.id.tv_text); + tv_text.setText(message); + if(dialog==null){ + dialog = new Dialog(context, R.style.transparentFrameWindowStyle); + dialog.setContentView(view); + dialog.setCanceledOnTouchOutside(false); + } + dialog.show(); + return dialog; + } + + public void setMessage(String message) { + if (tv_text != null) { + tv_text.setText(message); + } + } + + public void dismiss() { + if (dialog != null) { + dialog.dismiss(); + } + } + + public boolean isShowing() { + if (dialog != null) { + return dialog.isShowing(); + } else { + return false; + } + + } +} \ No newline at end of file diff --git a/libray_lxndroid/src/main/res/drawable/arrow_back.png b/libray_lxndroid/src/main/res/drawable/arrow_back.png new file mode 100644 index 0000000..f7c95d4 Binary files /dev/null and b/libray_lxndroid/src/main/res/drawable/arrow_back.png differ diff --git a/libray_lxndroid/src/main/res/drawable/loading_bg.9.png b/libray_lxndroid/src/main/res/drawable/loading_bg.9.png new file mode 100644 index 0000000..aa325e1 Binary files /dev/null and b/libray_lxndroid/src/main/res/drawable/loading_bg.9.png differ diff --git a/libray_lxndroid/src/main/res/drawable/transparent_bg.xml b/libray_lxndroid/src/main/res/drawable/transparent_bg.xml new file mode 100644 index 0000000..7ba8e7f --- /dev/null +++ b/libray_lxndroid/src/main/res/drawable/transparent_bg.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/libray_lxndroid/src/main/res/layout/ac_title.xml b/libray_lxndroid/src/main/res/layout/ac_title.xml new file mode 100644 index 0000000..fac025f --- /dev/null +++ b/libray_lxndroid/src/main/res/layout/ac_title.xml @@ -0,0 +1,21 @@ + + + + + + + + + + \ No newline at end of file diff --git a/libray_lxndroid/src/main/res/layout/loading.xml b/libray_lxndroid/src/main/res/layout/loading.xml new file mode 100644 index 0000000..dd0abe6 --- /dev/null +++ b/libray_lxndroid/src/main/res/layout/loading.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + diff --git a/libray_lxndroid/src/main/res/layout/public_titlebar.xml b/libray_lxndroid/src/main/res/layout/public_titlebar.xml new file mode 100644 index 0000000..088414e --- /dev/null +++ b/libray_lxndroid/src/main/res/layout/public_titlebar.xml @@ -0,0 +1,62 @@ + + + + + + + + + + \ No newline at end of file diff --git a/libray_lxndroid/src/main/res/values/attrs.xml b/libray_lxndroid/src/main/res/values/attrs.xml new file mode 100644 index 0000000..e07d020 --- /dev/null +++ b/libray_lxndroid/src/main/res/values/attrs.xml @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/libray_lxndroid/src/main/res/values/strings.xml b/libray_lxndroid/src/main/res/values/strings.xml new file mode 100644 index 0000000..e3a7072 --- /dev/null +++ b/libray_lxndroid/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + My Library + diff --git a/libray_lxndroid/src/main/res/values/styles.xml b/libray_lxndroid/src/main/res/values/styles.xml new file mode 100644 index 0000000..99f0630 --- /dev/null +++ b/libray_lxndroid/src/main/res/values/styles.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + diff --git a/libray_lxndroid/src/test/java/com/kejiang/yuandl/ExampleUnitTest.java b/libray_lxndroid/src/test/java/com/kejiang/yuandl/ExampleUnitTest.java new file mode 100644 index 0000000..601f284 --- /dev/null +++ b/libray_lxndroid/src/test/java/com/kejiang/yuandl/ExampleUnitTest.java @@ -0,0 +1,15 @@ +package com.kejiang.yuandl; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * To work on unit tests, switch the Test Artifact in the Build Variants view. + */ +public class ExampleUnitTest { + @Test + public void addition_isCorrect() throws Exception { + assertEquals(4, 2 + 2); + } +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..3fc353d --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +include ':app', ':libray_lxndroid'