├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── strings.xml
│ │ │ │ ├── attrs.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ └── layout
│ │ │ │ ├── list_item.xml
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ ├── zjw
│ │ │ │ └── appmethodtime
│ │ │ │ │ ├── CostTime.java
│ │ │ │ │ ├── SearchCoreModel.java
│ │ │ │ │ ├── SearchShopModel.java
│ │ │ │ │ ├── BaseModel.java
│ │ │ │ │ ├── DPIUtil.java
│ │ │ │ │ ├── FlexBoxMaxLinesLayout.java
│ │ │ │ │ ├── MyApplication.java
│ │ │ │ │ ├── MainActivity.kt
│ │ │ │ │ ├── HoldTagSpan.java
│ │ │ │ │ ├── Truss.java
│ │ │ │ │ ├── GradientTextView.java
│ │ │ │ │ ├── ViewDragHelperLayout.java
│ │ │ │ │ └── EllipsizedTextView.java
│ │ │ │ └── tablayout
│ │ │ │ ├── PageTransformerListener.java
│ │ │ │ ├── ScaleTitleView.java
│ │ │ │ └── ClipPagerFrameLayout.java
│ │ └── AndroidManifest.xml
│ ├── androidTest
│ │ └── java
│ │ │ └── com
│ │ │ └── zjw
│ │ │ └── appmethodtime
│ │ │ └── ExampleInstrumentedTest.java
│ └── test
│ │ └── java
│ │ └── com
│ │ └── zjw
│ │ └── appmethodtime
│ │ └── ExampleUnitTest.java
├── proguard-rules.pro
└── build.gradle
├── customlint
├── .gitignore
├── build.gradle
└── src
│ └── main
│ └── java
│ └── com
│ └── zjw
│ └── customlint
│ ├── CustomIssueRegistry.java
│ └── MyLogDetector.java
├── mylibrary
├── .gitignore
├── classes.jar
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ └── strings.xml
│ │ │ └── layout
│ │ │ │ └── activity_lib.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── zjw
│ │ │ │ └── mylibrary
│ │ │ │ ├── Bean.java
│ │ │ │ └── LibActivity.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── zjw
│ │ │ └── mylibrary
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── zjw
│ │ └── mylibrary
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── myapplication
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── drawable
│ │ │ │ ├── location.png
│ │ │ │ ├── location_night.png
│ │ │ │ ├── location_normal.png
│ │ │ │ └── location_selector.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ └── layout
│ │ │ │ └── app_lib_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── zjw
│ │ │ │ └── myapplication
│ │ │ │ └── MyLibActivity.java
│ │ ├── release
│ │ │ └── AndroidManifest.xml
│ │ └── debug
│ │ │ └── AndroidManifest.xml
│ └── test
│ │ └── java
│ │ └── com
│ │ └── zjw
│ │ └── myapplication
│ │ └── ExampleUnitTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── gradlew
└── README.md
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/customlint/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/mylibrary/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/myapplication/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':mylibrary', ':customLint', ':buildSrc'
2 |
--------------------------------------------------------------------------------
/mylibrary/classes.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/mylibrary/classes.jar
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/mylibrary/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | My Library
3 |
4 |
--------------------------------------------------------------------------------
/myapplication/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | MyApplication
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/drawable/location.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/drawable/location.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/drawable/location_night.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/drawable/location_night.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/drawable/location_normal.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/drawable/location_normal.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/zjw/mylibrary/Bean.java:
--------------------------------------------------------------------------------
1 | package com.zjw.mylibrary;
2 |
3 | /**
4 | * Created by hasee on 2017/5/8.
5 | */
6 |
7 | public class Bean {
8 | }
9 |
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/myapplication/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjw-swun/AppMethodTime/HEAD/myapplication/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | /.idea
7 | .DS_Store
8 | /build
9 | /captures
10 | .externalNativeBuild
11 | /repo/
--------------------------------------------------------------------------------
/myapplication/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Jun 28 22:34:50 CST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 | #4D97FF
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AppMethodTime
3 | Main3Activity
4 | Main4Activity
5 | Main2Activity
6 |
7 |
--------------------------------------------------------------------------------
/myapplication/src/main/res/drawable/location_selector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/CostTime.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | /**
9 | * Created by hasee on 2017/5/2.
10 | */
11 | @Retention(RetentionPolicy.RUNTIME)
12 | @Target(ElementType.METHOD)
13 | public @interface CostTime {
14 | }
15 |
--------------------------------------------------------------------------------
/myapplication/src/main/java/com/zjw/myapplication/MyLibActivity.java:
--------------------------------------------------------------------------------
1 | package com.zjw.myapplication;
2 |
3 | import androidx.appcompat.app.AppCompatActivity;
4 | import android.os.Bundle;
5 |
6 | public class MyLibActivity extends AppCompatActivity {
7 |
8 | @Override
9 | protected void onCreate(Bundle savedInstanceState) {
10 | super.onCreate(savedInstanceState);
11 | setContentView(R.layout.app_lib_main);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/mylibrary/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/myapplication/src/main/release/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/myapplication/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/customlint/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java-library'
2 |
3 | dependencies {
4 | implementation fileTree(dir: 'libs', include: ['*.jar'])
5 |
6 | compileOnly "com.android.tools.lint:lint-api:26.4.2"
7 | compileOnly "com.android.tools.lint:lint-checks:26.4.2"
8 | }
9 |
10 | sourceCompatibility = "1.8"
11 | targetCompatibility = "1.8"
12 |
13 | jar {
14 | manifest {
15 | attributes("Lint-Registry-v2": "com.zjw.customlint.CustomIssueRegistry")
16 | }
17 | }
--------------------------------------------------------------------------------
/mylibrary/src/test/java/com/zjw/mylibrary/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.zjw.mylibrary;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/myapplication/src/test/java/com/zjw/myapplication/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.zjw.myapplication;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/zjw/mylibrary/LibActivity.java:
--------------------------------------------------------------------------------
1 | package com.zjw.mylibrary;
2 |
3 | import androidx.appcompat.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.util.Log;
6 | import android.widget.TextView;
7 |
8 | public class LibActivity extends AppCompatActivity {
9 |
10 | @Override
11 | protected void onCreate(Bundle savedInstanceState) {
12 | super.onCreate(savedInstanceState);
13 | setContentView(R.layout.activity_lib);
14 | final TextView viewById = findViewById(R.id.mTextView);
15 | Log.e("tag","test");
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/SearchCoreModel.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | public class SearchCoreModel extends BaseModel {
6 | @SerializedName(value = "title")
7 | public String base;
8 |
9 | public String getBase() {
10 | return base;
11 | }
12 |
13 | public void setBase(String base) {
14 | this.base = base;
15 | }
16 |
17 | @Override
18 | public String toString() {
19 | return "SearchCoreModel{" +
20 | "base='" + base + '\'' +
21 | '}'+super.toString();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/SearchShopModel.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | public class SearchShopModel extends SearchCoreModel {
6 | @SerializedName(value = "title")
7 | public String shop;
8 |
9 | public String getShop() {
10 | return shop;
11 | }
12 |
13 | public void setShop(String shop) {
14 | this.shop = shop;
15 | }
16 |
17 | @Override
18 | public String toString() {
19 | return "SearchShopModel{" +
20 | "shop='" + shop + '\'' +
21 | '}' + super.toString();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/BaseModel.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | public class BaseModel {
4 | private int age;
5 | private String name = "test";
6 |
7 | public int getAge() {
8 | return age;
9 | }
10 |
11 | public void setAge(int age) {
12 | this.age = age;
13 | }
14 |
15 | public String getName() {
16 | return name;
17 | }
18 |
19 | public void setName(String name) {
20 | this.name = name;
21 | }
22 |
23 | @Override
24 | public String toString() {
25 | return "BaseModel{" +
26 | "age=" + age +
27 | ", name='" + name + '\'' +
28 | '}';
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/app/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tablayout/PageTransformerListener.java:
--------------------------------------------------------------------------------
1 | package com.tablayout;
2 |
3 |
4 | interface PageTransformerListener {
5 | void setDirection(Direction direction);
6 |
7 | void setCurrentProgress(float currentProgress);
8 |
9 | void setVisibility(int visibility);
10 |
11 | enum Direction {
12 | LEFT_TO_RIGHT, RIGHT_TO_LIFT
13 | }
14 |
15 | /**
16 | * 离开
17 | *
18 | * @param leavePercent 离开的百分比, 0.0f - 1.0f
19 | * @param leftToRight 从左至右离开
20 | */
21 | void onLeave(int index, float leavePercent, boolean leftToRight);
22 |
23 | /**
24 | * 进入
25 | *
26 | * @param enterPercent 进入的百分比, 0.0f - 1.0f
27 | * @param leftToRight 从左至右离开
28 | */
29 | void onEnter(int index, float enterPercent, boolean leftToRight);
30 | }
31 |
--------------------------------------------------------------------------------
/myapplication/src/main/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/mylibrary/src/main/res/layout/activity_lib.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
18 |
19 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | android.enableJetifier=true
13 | android.useAndroidX=true
14 | org.gradle.jvmargs=-Xmx1536m
15 |
16 | # When configured, Gradle will run in incubating parallel mode.
17 | # This option should only be used with decoupled projects. More details, visit
18 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
19 | # org.gradle.parallel=true
20 |
21 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/zjw/appmethodtime/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.zjw.appmethodtime", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/mylibrary/src/androidTest/java/com/zjw/mylibrary/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.zjw.mylibrary;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.zjw.mylibrary.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/customlint/src/main/java/com/zjw/customlint/CustomIssueRegistry.java:
--------------------------------------------------------------------------------
1 | package com.zjw.customlint;
2 |
3 | import com.android.tools.lint.checks.LogDetector;
4 | import com.android.tools.lint.client.api.IssueRegistry;
5 | import com.android.tools.lint.detector.api.ApiKt;
6 | import com.android.tools.lint.detector.api.Issue;
7 |
8 | import org.jetbrains.annotations.NotNull;
9 |
10 | import java.util.Arrays;
11 | import java.util.List;
12 |
13 |
14 | /**
15 | * Created by Omooo
16 | * Date:2019-07-04
17 | */
18 | @SuppressWarnings("UnstableApiUsage")
19 | public class CustomIssueRegistry extends IssueRegistry {
20 |
21 | @NotNull
22 | @Override
23 | public List getIssues() {
24 |
25 | return Arrays.asList(
26 | //自定义lint 尽量不要和android 原有Lint重名 例如
27 | //com.android.tools.lint.checks.LogDetector
28 | MyLogDetector.ISSUE
29 | );
30 | }
31 |
32 | @Override
33 | public int getApi() {
34 | return ApiKt.CURRENT_API;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/myapplication/src/main/res/layout/app_lib_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Application\Android\sdkUpDate/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/mylibrary/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Application\Android\sdkUpDate/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/myapplication/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Application\Android\sdkUpDate/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/list_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
14 |
15 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/DPIUtil.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import android.content.Context;
4 |
5 |
6 |
7 | public class DPIUtil {
8 |
9 |
10 | public static int dip2px(Context context, float dipValue) {
11 | if (context == null) {
12 | return 0;
13 | }
14 | float density = context.getResources().getDisplayMetrics().density;
15 | return (int) (dipValue * density + 0.5f);
16 | }
17 |
18 | public static int px2dip(Context context, float pxValue) {
19 | if (context == null) {
20 | return 0;
21 | }
22 | float density = context.getResources().getDisplayMetrics().density;
23 | return (int) (pxValue / density + 0.5f);
24 | }
25 |
26 |
27 | public static int px2sp(Context context, float pxValue) {
28 | final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
29 | return (int) (pxValue / fontScale + 0.5f);
30 | }
31 |
32 |
33 | public static int sp2px(Context context, float spValue) {
34 | final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
35 | return (int) (spValue * fontScale + 0.5f);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
19 |
24 |
25 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/myapplication/build.gradle:
--------------------------------------------------------------------------------
1 | project.extensions.add("isBuildModule", false)
2 | def isBuildModule = project.extensions.getByName("isBuildModule")
3 |
4 | println("isBuildModule is " + isBuildModule)
5 |
6 | if (isBuildModule) {
7 | apply plugin: 'com.android.application'
8 | } else {
9 | apply plugin: 'com.android.library'
10 | }
11 | android {
12 | compileSdkVersion 25
13 | buildToolsVersion "25.0.2"
14 |
15 | defaultConfig {
16 | if (isBuildModule) {
17 | applicationId "com.zjw.myapplication"
18 | }
19 | minSdkVersion 14
20 | targetSdkVersion 25
21 | versionCode 1
22 | versionName "1.0"
23 |
24 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
25 |
26 | }
27 | buildTypes {
28 | release {
29 | minifyEnabled false
30 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
31 | }
32 | }
33 |
34 | sourceSets {
35 | main {
36 | if (isBuildModule) {
37 | manifest.srcFile 'src/main/debug/AndroidManifest.xml'
38 | } else {
39 | manifest.srcFile 'src/main/release/AndroidManifest.xml'
40 | }
41 | }
42 | }
43 | }
44 |
45 | dependencies {
46 | compile fileTree(dir: 'libs', include: ['*.jar'])
47 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
48 | exclude group: 'com.android.support', module: 'support-annotations'
49 | })
50 | compile 'com.android.support:appcompat-v7:25.3.1'
51 | compile 'com.android.support.constraint:constraint-layout:1.0.2'
52 | testCompile 'junit:junit:4.12'
53 | }
54 |
55 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/FlexBoxMaxLinesLayout.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import android.content.Context;
4 | import android.util.AttributeSet;
5 |
6 | import com.google.android.flexbox.FlexLine;
7 | import com.google.android.flexbox.FlexboxLayout;
8 |
9 | import java.util.List;
10 |
11 | /**
12 | * FlexboxLayout设置maxLines之后,如果item超出maxLines,会全部罗列在最后一行,不符合需求;
13 | *
14 | * FlexBoxLayoutMaxLines支持设置MaxLines,并截断超出MaxLines的内容;
15 | */
16 | public class FlexBoxMaxLinesLayout extends FlexboxLayout {
17 | private int maxLines = NOT_SET;
18 |
19 | @Override
20 | public void setMaxLine(int maxLine) {
21 | maxLines = maxLine;
22 | }
23 |
24 | public int getMaxLines() {
25 | return maxLines;
26 | }
27 |
28 | /**
29 | * see {@link #getMaxLines()}
30 | */
31 | @Deprecated
32 | @Override
33 | public int getMaxLine() {
34 | return NOT_SET;
35 | }
36 |
37 | public FlexBoxMaxLinesLayout(Context context) {
38 | this(context, null);
39 | }
40 |
41 | public FlexBoxMaxLinesLayout(Context context, AttributeSet attrs) {
42 | this(context, attrs, 0);
43 | }
44 |
45 | public FlexBoxMaxLinesLayout(Context context, AttributeSet attrs, int defStyleAttr) {
46 | super(context, attrs, defStyleAttr);
47 | setMaxLine(super.getMaxLine());
48 | super.setMaxLine(NOT_SET);
49 | }
50 |
51 | @Override
52 | public List getFlexLinesInternal() {
53 | List flexLines = super.getFlexLinesInternal();
54 | int size = flexLines.size();
55 | if (maxLines > 0 && size > maxLines) {
56 | flexLines.subList(maxLines, size).clear();
57 | }
58 | return flexLines;
59 | }
60 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/MyApplication.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 | import android.content.res.Configuration;
6 | import android.util.Log;
7 |
8 | import com.google.gson.Gson;
9 |
10 | /**
11 | * Created by hasee on 2017/6/5.
12 | */
13 |
14 | public class MyApplication extends Application {
15 |
16 | @Override
17 | public void onConfigurationChanged(Configuration newConfig) {
18 | super.onConfigurationChanged(newConfig);
19 | }
20 |
21 | @Override
22 | public void onCreate() {
23 | super.onCreate();
24 | //自定义MyLogDetector lint error提示
25 | Log.i("TAG", "啊啊啊啊,我被发现了!");
26 | Test(new Gson());
27 | test();
28 | test1();
29 | }
30 |
31 | void test(){
32 | long startTime = System.nanoTime();
33 | System.nanoTime();
34 | long endTime = System.nanoTime();
35 | Log.i("TAG", "test cost is " + ((endTime - startTime)*1.0f / 1000000f));
36 | }
37 |
38 | //test cost is 0.001042 (说明System.nanoTime()要占0.001042毫秒)
39 | //test1 cost is 0.013073 (说明log本身要占0.01毫秒)
40 | //所以我们只需要关注 精度到0.1毫秒
41 | void test1(){
42 | long startTime = System.nanoTime();
43 | Log.i("TAG", "log cost is " + (100-50) / 1000000f);
44 | long endTime = System.nanoTime();
45 | Log.i("TAG", "test1 cost is " + (endTime - startTime)*1.0 / 1000000f);
46 | }
47 |
48 | @Override
49 | protected void attachBaseContext(Context base) {
50 | super.attachBaseContext(base);
51 | }
52 |
53 | @Override
54 | public void onTerminate() {
55 | super.onTerminate();
56 | }
57 |
58 | private void Test(Gson gson){
59 | Log.e("TAG",""+gson.toString());
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime
2 |
3 | import android.os.Bundle
4 | import android.util.Log
5 | import android.view.View
6 | import androidx.appcompat.app.AppCompatActivity
7 | import kotlinx.android.synthetic.main.activity_main.*
8 |
9 | class MainActivity : AppCompatActivity(), View.OnClickListener {
10 |
11 | private val TAG = "TAG"
12 |
13 | @CostTime
14 | override fun onCreate(savedInstanceState: Bundle?) {
15 | val startTime = System.nanoTime()
16 | super.onCreate(savedInstanceState)
17 | super.setContentView(R.layout.activity_main)
18 | initView()
19 | val endTime = System.nanoTime()
20 | Log.i("TAG","onCreate cost is "+(endTime - startTime)/1000000f)
21 | }
22 |
23 | @CostTime
24 | private fun initView() {
25 | mTextView.setOnClickListener(this@MainActivity)
26 | //android官方 lint插件自带的warring提示
27 | //自定义MyLogDetector lint error提示
28 | // Log.e(TAG,"test")
29 | test()
30 | test1()
31 | }
32 |
33 | fun test(){
34 | val startTime = System.nanoTime()
35 | System.nanoTime()
36 | val endTime = System.nanoTime()
37 | Log.i("TAG", "test cost is " + (endTime - startTime) / 1000000f)
38 | }
39 |
40 | fun test1(){
41 | val startTime = System.nanoTime()
42 | Log.i("TAG", "log cost is " + (100-50) / 1000000f)
43 | val endTime = System.nanoTime()
44 | Log.i("TAG", "test1 cost is " + (endTime - startTime) / 1000000f)
45 | }
46 | @CostTime
47 | override fun onClick(view: View) {
48 | if (view.id == R.id.mTextView) {
49 | try {
50 | Thread.sleep(500)
51 | } catch (e: Exception) {
52 | }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/app/src/test/java/com/zjw/appmethodtime/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import org.junit.Test;
4 |
5 | import java.io.File;
6 |
7 | import javassist.ClassPath;
8 | import javassist.ClassPool;
9 | import javassist.CtClass;
10 | import javassist.CtMethod;
11 |
12 | import static org.junit.Assert.*;
13 |
14 | /**
15 | * Example local unit test, which will execute on the development machine (host).
16 | *
17 | * @see Testing documentation
18 | */
19 | public class ExampleUnitTest {
20 | @Test
21 | public void addition_isCorrect() throws Exception {
22 | assertEquals(4, 2 + 2);
23 | }
24 |
25 | @Test
26 | public void testClassOperate(){
27 | ClassPool pool = ClassPool.getDefault();
28 | String fullClass = "/Users/hana/StudioProjects/AppMethodTime/app/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/com/zjw/appmethodtime/MyApplication.class";
29 |
30 | String parentPath = new File(fullClass).getParentFile().getAbsolutePath();
31 | String className = "com.zjw.appmethodtime.MyApplication";
32 | ClassPath classPath = null;
33 | try {
34 | classPath = pool.appendClassPath(parentPath);
35 | CtClass c = pool.getCtClass(className);
36 | if (c.isFrozen()) {
37 | c.defrost();
38 | }
39 | CtMethod[] methods = c.getDeclaredMethods();
40 | for (CtMethod method : methods){
41 | System.out.println(method.getName() + method.getMethodInfo().getCodeAttribute().toString());
42 | }
43 | }catch (Throwable e){
44 | e.printStackTrace();
45 | }finally {
46 | if (classPath != null) {
47 | pool.removeClassPath(classPath);
48 | }
49 | }
50 | }
51 | }
--------------------------------------------------------------------------------
/mylibrary/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: com.zjw.plugin.MyPlugin
3 |
4 | android {
5 | compileSdkVersion 28
6 | buildToolsVersion "28.0.3"
7 |
8 | defaultConfig {
9 | minSdkVersion 14
10 | targetSdkVersion 28
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
15 |
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | signingConfig signingConfigs.debug
22 | }
23 | }
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 | implementation 'androidx.appcompat:appcompat:1.0.0'
29 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
30 | lintChecks project(":customLint")
31 | }
32 |
33 | AppMethodTime {
34 | //enabled默认值为true
35 | //enabled = true 表示允许插入函数耗时测量代码
36 | //enabled = false 表示不允许插入函数耗时测量代码
37 | enabled = true
38 |
39 | //useCostTime默认值为true
40 | // useCostTime = true 表示本lib module或本application module中build\intermediates\classes\debug目录下
41 | // class对应java文件中带有CostTime注解的方法才会在编译成class时被插入函数耗时测量代码,
42 |
43 | // useCostTime = false 表示本lib module或本application module中build\intermediates\classes\debug目录下
44 | // class对应java文件所有书写的方法均会在编译成class时被插入数耗时测量代码
45 | useCostTime = false
46 |
47 | //showLog默认值为false
48 | // showLog = true 表示允许在Gradle Console中输出插入函数耗时测量代码过程中的Log
49 | // showLog = false 表示不允许在Gradle Console中输出插入函数耗时测量代码过程中的Log
50 | showLog = false
51 |
52 | //aarOrJarPath 需要使用 other:appMethodJarOrAar 任务单独执行
53 | //aarOrJarPath = "D:\\Github\\AppMethodTime\\mylibrary\\build\\outputs\\aar\\mylibrary-debug.aar"
54 | //aarOrJarPath = "D:\\Github\\AppMethodTime\\mylibrary\\build\\outputs\\aar\\Target_temp.jar"
55 | }
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/HoldTagSpan.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import android.graphics.Canvas;
4 | import android.graphics.Paint;
5 | import android.text.style.ReplacementSpan;
6 |
7 | /**
8 | * 占位使用的Span
9 | * 使用案例 textview?.measure(0, 0) //textview为targetTv要嵌入的view 可以是任意view
10 | * val truss = Truss()
11 | * val span = HoldTagSpan(textview?.measuredWidth!! + textview?.measuredWidth!!,
12 | * 1)
13 | * truss.pushSpan(span)
14 | * .append("tag")
15 | * .popSpan()
16 | * .append(mData?.questionTitle)
17 | * targetTv?.text = truss.build()
18 | *
19 | */
20 | public class HoldTagSpan extends ReplacementSpan {
21 | private int width;
22 | private int height;
23 | private int leftMargin;
24 | private int rightMargin;
25 |
26 | public HoldTagSpan(int width, int height) {
27 | this.width = width;
28 | this.height = height;
29 | }
30 |
31 | public HoldTagSpan(int width, int height, int leftMargin, int rightMargin) {
32 | this.width = width;
33 | this.height = height;
34 | this.leftMargin = leftMargin;
35 | this.rightMargin = rightMargin;
36 | }
37 |
38 | public HoldTagSpan setLeftMargin(int leftMargin) {
39 | this.leftMargin = leftMargin;
40 | return this;
41 | }
42 |
43 | public HoldTagSpan setRightMargin(int rightMargin) {
44 | this.rightMargin = rightMargin;
45 | return this;
46 | }
47 |
48 |
49 | @Override
50 | public int getSize(@androidx.annotation.NonNull Paint paint, CharSequence charSequence, int start, int end, @androidx.annotation.Nullable Paint.FontMetricsInt fontMetricsInt) {
51 | return width + leftMargin + rightMargin;
52 | }
53 |
54 | @Override
55 | public void draw(@androidx.annotation.NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @androidx.annotation.NonNull Paint paint) {
56 | }
57 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/Truss.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import android.text.SpannableStringBuilder;
4 |
5 | import java.util.ArrayDeque;
6 |
7 | import static android.text.Spanned.SPAN_INCLUSIVE_EXCLUSIVE;
8 |
9 | /**
10 | * A {@link SpannableStringBuilder} wrapper whose API doesn't make me want to stab my eyes out.
11 | *
12 | * @see JakeWharton-Truss
13 | */
14 | public class Truss {
15 | private final SpannableStringBuilder builder;
16 | private final java.util.Deque stack;
17 |
18 | public Truss() {
19 | builder = new SpannableStringBuilder();
20 | stack = new ArrayDeque<>();
21 | }
22 |
23 | public Truss append(String string) {
24 | builder.append(string);
25 | return this;
26 | }
27 |
28 | public Truss append(CharSequence charSequence) {
29 | builder.append(charSequence);
30 | return this;
31 | }
32 |
33 | public Truss append(char c) {
34 | builder.append(c);
35 | return this;
36 | }
37 |
38 | public Truss append(int number) {
39 | builder.append(String.valueOf(number));
40 | return this;
41 | }
42 |
43 | /**
44 | * Starts {@code span} at the current position in the builder.
45 | */
46 | public Truss pushSpan(Object span) {
47 | stack.addLast(new Span(builder.length(), span));
48 | return this;
49 | }
50 |
51 | /**
52 | * End the most recently pushed span at the current position in the builder.
53 | */
54 | public Truss popSpan() {
55 | Span span = stack.removeLast();
56 | builder.setSpan(span.span, span.start, builder.length(), SPAN_INCLUSIVE_EXCLUSIVE);
57 | return this;
58 | }
59 |
60 | /**
61 | * Create the final {@link CharSequence}, popping any remaining spans.
62 | */
63 | public CharSequence build() {
64 | while (!stack.isEmpty()) {
65 | popSpan();
66 | }
67 | return builder;
68 | }
69 |
70 | private static final class Span {
71 | final int start;
72 | final Object span;
73 |
74 | public Span(int start, Object span) {
75 | this.start = start;
76 | this.span = span;
77 | }
78 | }
79 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/tablayout/ScaleTitleView.java:
--------------------------------------------------------------------------------
1 | package com.tablayout;
2 |
3 | import android.content.Context;
4 | import android.util.AttributeSet;
5 | import android.view.View;
6 | import android.view.animation.Interpolator;
7 | import android.view.animation.LinearInterpolator;
8 |
9 | import androidx.appcompat.widget.AppCompatTextView;
10 |
11 | public class ScaleTitleView extends AppCompatTextView implements PageTransformerListener {
12 |
13 | private float mCurrentProgress;
14 | private Direction mDirection = Direction.LEFT_TO_RIGHT;
15 | private float mSelectedSize = 22;
16 | private float mUnSelectedSize = 16;
17 | private float mTextSize = mUnSelectedSize;
18 | private Interpolator mInterpolator = new LinearInterpolator();
19 | private View mIndicator;
20 | private float mMinScale = 0.75f;
21 |
22 |
23 | public ScaleTitleView(Context context) {
24 | super(context);
25 | }
26 |
27 | public ScaleTitleView(Context context, AttributeSet attrs) {
28 | super(context, attrs);
29 | }
30 |
31 | public ScaleTitleView(Context context, AttributeSet attrs, int defStyleAttr) {
32 | super(context, attrs, defStyleAttr);
33 | }
34 |
35 | @Override
36 | public void setCurrentProgress(float currentProgress) {
37 | mCurrentProgress = currentProgress;
38 | }
39 |
40 | @Override
41 | public void onLeave(int index, float leavePercent, boolean leftToRight) {
42 | setScaleX(1.0f + (mMinScale - 1.0f) * leavePercent);
43 | setScaleY(1.0f + (mMinScale - 1.0f) * leavePercent);
44 | if (mIndicator != null) {
45 | mIndicator.setAlpha(1 - leavePercent);
46 | }
47 | }
48 |
49 | @Override
50 | public void onEnter(int index, float enterPercent, boolean leftToRight) {
51 | setScaleX(mMinScale + (1.0f - mMinScale) * enterPercent);
52 | setScaleY(mMinScale + (1.0f - mMinScale) * enterPercent);
53 | if (mIndicator != null) {
54 | mIndicator.setAlpha(enterPercent);
55 | }
56 | }
57 |
58 | @Override
59 | public void setDirection(Direction direction) {
60 | mDirection = direction;
61 | }
62 |
63 | public View getIndicator() {
64 | return mIndicator;
65 | }
66 |
67 | public void setIndicator(View indicator) {
68 | mIndicator = indicator;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | apply plugin: com.zjw.plugin.MyPlugin
6 |
7 |
8 | AppMethodTime {
9 | //enabled默认值为true
10 | //enabled = true 表示允许插入函数耗时测量代码
11 | //enabled = false 表示不允许插入函数耗时测量代码
12 | enabled = true
13 |
14 | //useCostTime默认值为true
15 | // useCostTime = true 表示本lib module或本application module 中带有CostTime注解的方法才会在编译成class时被插入函数耗时测量代码,
16 | // useCostTime = false 表示所有非抽象方法均会在编译成class时被插入数耗时测量代码
17 | useCostTime = false
18 |
19 | //showLog默认值为true
20 | // showLog = true 表示允许在Gradle Console中输出插入函数耗时测量代码过程中的Log
21 | // showLog = false 表示不允许在Gradle Console中输出插入函数耗时测量代码过程中的Log
22 | showLog = false
23 |
24 | //enableOrder默认值为false 表示是否允许插入打印方法调用顺序log
25 | enableOrder = false
26 |
27 | //limitTimeMilli 单位毫秒 默认值为-1 表示不设置打印方法门槛值,如设100表示只打印耗时>=100ms的方法
28 | limitTimeMilli = -1
29 |
30 | //warringTimeMilli 单位毫秒 默认值为16 表示打印耗时log时附加一个预警信息
31 | warringTimeMilli = 16
32 | }
33 |
34 | android {
35 | compileSdkVersion 28
36 | buildToolsVersion "28.0.3"
37 |
38 | defaultConfig {
39 | applicationId "com.zjw.appmethodtime"
40 | minSdkVersion 21
41 | targetSdkVersion 28
42 | versionCode 1
43 | versionName "1.0"
44 | multiDexEnabled true
45 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
46 | }
47 |
48 | compileOptions {
49 | sourceCompatibility 1.8
50 | targetCompatibility 1.8
51 | }
52 |
53 | buildTypes {
54 | release {
55 | minifyEnabled false
56 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
57 | signingConfig signingConfigs.debug
58 | }
59 | }
60 |
61 | lintOptions {
62 | checkReleaseBuilds false
63 | abortOnError false
64 | }
65 | }
66 | dependencies {
67 | implementation fileTree(dir: 'libs', include: ['*.jar'])
68 | implementation 'androidx.appcompat:appcompat:1.3.0'
69 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
70 | implementation 'com.google.android.material:material:1.3.0'
71 | implementation 'com.google.code.gson:gson:2.8.5'
72 | implementation 'com.squareup.retrofit2:retrofit:2.7.1'
73 | implementation 'com.squareup.retrofit2:converter-gson:2.7.1'
74 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
75 | implementation 'androidx.customview:customview:1.1.0'
76 |
77 | testImplementation 'junit:junit:4.12'
78 | implementation 'org.javassist:javassist:3.20.0-GA'
79 | implementation 'com.google.android:flexbox:1.1.1'
80 | }
81 |
82 |
83 |
84 | /**
85 | * 需要在执行 ssembleDebug Task 之前挂载 lintDebug
86 | */
87 | /*
88 | project.afterEvaluate {
89 | def assembleDebugTask = project.tasks.find { it.name == 'assembleDebug' }
90 | def lintTask = project.tasks.find { it.name == 'lintDebug' }
91 | assembleDebugTask.dependsOn(lintTask)
92 | }
93 | */
94 |
95 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tablayout/ClipPagerFrameLayout.java:
--------------------------------------------------------------------------------
1 | package com.tablayout;
2 |
3 | import android.content.Context;
4 | import android.graphics.Outline;
5 | import android.graphics.Rect;
6 | import android.util.AttributeSet;
7 | import android.view.View;
8 | import android.view.ViewOutlineProvider;
9 | import android.widget.FrameLayout;
10 |
11 | import androidx.annotation.NonNull;
12 | import androidx.annotation.Nullable;
13 |
14 | public class ClipPagerFrameLayout extends FrameLayout implements PageTransformerListener{
15 | private float mCurrentProgress;
16 | private float mClipLeft;
17 | private float mClipRight;
18 | private Direction mDirection = Direction.LEFT_TO_RIGHT;
19 | private Rect mRect = new Rect();
20 | private ClipViewOutlineProvider mClipViewOutlineProvider;
21 |
22 |
23 | public ClipPagerFrameLayout(@NonNull Context context) {
24 | this(context, null);
25 | }
26 |
27 | public ClipPagerFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
28 | this(context, attrs, 0);
29 |
30 | }
31 |
32 | public ClipPagerFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
33 | super(context, attrs, defStyleAttr);
34 | mClipViewOutlineProvider = new ClipViewOutlineProvider();
35 | setOutlineProvider(mClipViewOutlineProvider);
36 | setClipToOutline(true);
37 | }
38 |
39 |
40 | public float getCurrentProgress() {
41 | return mCurrentProgress;
42 | }
43 |
44 | @Override
45 | public void setCurrentProgress(float currentProgress) {
46 | mCurrentProgress = currentProgress;
47 | if (mDirection == Direction.LEFT_TO_RIGHT) {
48 | mRect.set(0, 0, (int) (getWidth() * mCurrentProgress), getHeight());
49 | } else {
50 | mRect.set((int) (getWidth() * (1 - mCurrentProgress)), 0, getWidth(), getHeight());
51 | }
52 | //setClipBounds(mRect);
53 | invalidateOutline();
54 | }
55 |
56 | @Override
57 | public void onLeave(int index, float leavePercent, boolean leftToRight) {
58 |
59 | }
60 |
61 | @Override
62 | public void onEnter(int index, float enterPercent, boolean leftToRight) {
63 |
64 | }
65 |
66 | private class ClipViewOutlineProvider extends ViewOutlineProvider {
67 | @Override
68 | public void getOutline(View view, Outline outline) {
69 | outline.setRect(mRect);
70 | }
71 | }
72 |
73 |
74 | public Direction getDirection() {
75 | return mDirection;
76 | }
77 |
78 | @Override
79 | public void setDirection(Direction direction) {
80 | mDirection = direction;
81 | }
82 |
83 | public float getClipLeft() {
84 | return mClipLeft;
85 | }
86 |
87 | public void setClipLeft(float clipLeft) {
88 | if (clipLeft <= 0) {
89 | clipLeft = 0;
90 | }
91 | mClipLeft = clipLeft;
92 | }
93 |
94 | public float getClipRight() {
95 | return mClipRight;
96 | }
97 |
98 | public void setClipRight(float clipRight) {
99 | if (clipRight >= getWidth()) {
100 | clipRight = getWidth();
101 | }
102 | mClipRight = clipRight;
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/customlint/src/main/java/com/zjw/customlint/MyLogDetector.java:
--------------------------------------------------------------------------------
1 | package com.zjw.customlint;
2 |
3 | import com.android.tools.lint.client.api.UElementHandler;
4 | import com.android.tools.lint.detector.api.Category;
5 | import com.android.tools.lint.detector.api.Detector;
6 | import com.android.tools.lint.detector.api.Implementation;
7 | import com.android.tools.lint.detector.api.Issue;
8 | import com.android.tools.lint.detector.api.JavaContext;
9 | import com.android.tools.lint.detector.api.Scope;
10 | import com.android.tools.lint.detector.api.Severity;
11 | import com.intellij.psi.PsiMethod;
12 |
13 | import org.jetbrains.annotations.NotNull;
14 | import org.jetbrains.annotations.Nullable;
15 | import org.jetbrains.uast.UCallExpression;
16 | import org.jetbrains.uast.UElement;
17 | import org.jetbrains.uast.util.UastExpressionUtils;
18 |
19 | import java.util.Collections;
20 | import java.util.List;
21 |
22 | /**
23 | * Created by Omooo
24 | * Date:2019-07-04
25 | * Desc:Avoid using Log class directly
26 | */
27 | @SuppressWarnings("UnstableApiUsage")
28 | public class MyLogDetector extends Detector implements Detector.UastScanner {
29 |
30 | public static final Issue ISSUE = Issue.create(
31 | //自定义lint id尽量不要和android 原有Lint重名
32 | "MyLogDetector",
33 | "Log Usage",
34 | "Please use the unified LogUtil class!",
35 | Category.CORRECTNESS,
36 | 6,
37 | Severity.FATAL,
38 | //Scope.JAVA_FILE_SCOPE :kotlin 文件也能显示这个提示
39 | new Implementation(MyLogDetector.class, Scope.JAVA_FILE_SCOPE)
40 | );
41 |
42 | @Nullable
43 | @Override
44 | public List> getApplicableUastTypes() {
45 | return Collections.singletonList(UCallExpression.class);
46 | }
47 |
48 | @Nullable
49 | @Override
50 | public UElementHandler createUastHandler(@NotNull JavaContext context) {
51 | return new LogHandler(context);
52 | }
53 |
54 | class LogHandler extends UElementHandler {
55 |
56 | private JavaContext context;
57 |
58 | LogHandler(JavaContext context) {
59 | this.context = context;
60 | }
61 |
62 | @Override
63 | public void visitCallExpression(@NotNull UCallExpression node) {
64 | if (!UastExpressionUtils.isMethodCall(node)) return;
65 | if (node.getReceiver() != null
66 | && node.getMethodName() != null) {
67 | String methodName = node.getMethodName();
68 | if (methodName.equals("i")
69 | || methodName.equals("d")
70 | || methodName.equals("e")
71 | || methodName.equals("v")
72 | || methodName.equals("w")
73 | || methodName.equals("wtf")) {
74 | PsiMethod method = node.resolve();
75 | if (context.getEvaluator().isMemberInClass(method, "android.util.Log")) {
76 | reportAllocation(context, node);
77 | }
78 | }
79 | }
80 | }
81 | }
82 |
83 | private void reportAllocation(JavaContext context, UCallExpression node) {
84 | context.report(ISSUE,
85 | node,
86 | context.getLocation(node),
87 | "\u21E2 Avoid using *Log* class directly"
88 | );
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/GradientTextView.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import android.content.Context;
4 | import android.content.res.TypedArray;
5 | import android.graphics.LinearGradient;
6 | import android.graphics.Shader;
7 | import android.util.AttributeSet;
8 |
9 | import androidx.appcompat.widget.AppCompatTextView;
10 |
11 |
12 | /**
13 | * 渐变颜色的TextView
14 | * Created by Dimitrios on 9/26/2017.
15 | */
16 | public class GradientTextView extends AppCompatTextView {
17 |
18 | private final static String TAG = GradientTextView.class.getSimpleName();
19 |
20 | private int[] mColors;
21 |
22 | private int mAngle = 0;
23 |
24 | private DIRECTION mDIRECTION;
25 |
26 | public enum DIRECTION {
27 | LEFT(0),
28 | TOP(90),
29 | RIGHT(180),
30 | BOTTOM(270);
31 |
32 | int angle;
33 |
34 | DIRECTION(int angle) {
35 | this.angle = angle;
36 | }
37 | }
38 |
39 | public GradientTextView(Context context) {
40 | super(context);
41 | init(context, null);
42 | }
43 |
44 | public GradientTextView(Context context, AttributeSet attrs) {
45 | super(context, attrs);
46 | init(context, attrs);
47 | }
48 |
49 | public GradientTextView(Context context, AttributeSet attrs, int defStyleAttr) {
50 | super(context, attrs, defStyleAttr);
51 | }
52 |
53 | @Override
54 | protected void onSizeChanged(int w, int h, int oldw, int oldh) {
55 | super.onSizeChanged(w, h, oldw, oldh);
56 | //if colors haven't been set, skip this
57 | if (mColors != null) {
58 | int[] xyPositions = calculateGradientPositions(w, h);
59 | Shader shader = new LinearGradient(xyPositions[0], xyPositions[1], xyPositions[2], xyPositions[3], mColors, null, Shader.TileMode.CLAMP);
60 | getPaint().setShader(shader);
61 | }
62 |
63 | }
64 |
65 | private int[] calculateGradientPositions(int w, int h) {
66 | int[] gradientPositions;
67 | if (mAngle < 0 || mAngle > 360) {
68 | }
69 | if (mDIRECTION != null) {
70 | switch (mDIRECTION) {
71 | case TOP:
72 | return new int[]{0, h, 0, 0};
73 | case RIGHT:
74 | return new int[]{0, 0, w, 0};
75 | case BOTTOM:
76 | return new int[]{0, 0, 0, h};
77 | case LEFT:
78 | default:
79 | return new int[]{w, 0, 0, 0};
80 | }
81 | }
82 | //should not reach here
83 | return new int[]{0, 0, 0, 0};
84 | }
85 |
86 | private void init(Context context, AttributeSet attributeSet) {
87 |
88 | final TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.GradientTextView);
89 |
90 | try {
91 | int colorArrayResourceId = typedArray.getResourceId(R.styleable.GradientTextView_gt_color_list, 0);
92 | if (colorArrayResourceId != 0) {
93 | mColors = getResources().getIntArray(colorArrayResourceId);
94 | }
95 | if (typedArray.hasValue(R.styleable.GradientTextView_gt_gradient_direction)) {
96 | int value = typedArray.getInt(R.styleable.GradientTextView_gt_gradient_direction, 0);
97 | mDIRECTION = DIRECTION.values()[value];
98 | }
99 |
100 | if (typedArray.hasValue(R.styleable.GradientTextView_gt_gradient_angle)) {
101 | mAngle = typedArray.getInt(R.styleable.GradientTextView_gt_gradient_angle, 0);
102 | }
103 |
104 | } catch (Exception ignored) {
105 | } finally {
106 | typedArray.recycle();
107 | }
108 | }
109 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/ViewDragHelperLayout.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import android.content.Context;
4 | import android.graphics.Point;
5 | import android.util.AttributeSet;
6 | import android.view.MotionEvent;
7 | import android.view.View;
8 | import android.widget.LinearLayout;
9 |
10 | import androidx.customview.widget.ViewDragHelper;
11 |
12 |
13 | public class ViewDragHelperLayout extends LinearLayout {
14 |
15 | private ViewDragHelper mDragger;
16 |
17 | private View mAutoBackView;
18 |
19 | private Point mAutoBackOriginPos = new Point();
20 |
21 | private int finalTop = -1;
22 |
23 | private OnExpandListenner onExpandListenner;
24 | private boolean isExpan;
25 | private boolean needDrag;
26 |
27 | public ViewDragHelperLayout(Context context) {
28 | super(context);
29 | init();
30 | }
31 |
32 | public ViewDragHelperLayout(Context context, AttributeSet attrs) {
33 | super(context, attrs);
34 | init();
35 | }
36 |
37 | private void init() {
38 | mDragger = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() {
39 | // 返回true,则表示可以捕获该view
40 | @Override
41 | public boolean tryCaptureView(View child, int pointerId) {
42 | // return true;
43 | if (!needDrag) {
44 | return false;
45 | }
46 | return child == mAutoBackView;
47 | }
48 |
49 | // 水平方向边界进行控制,left , top 分别为即将移动到的位置,如果返回固定的值,表示只能水平或垂直移动
50 | @Override
51 | public int clampViewPositionHorizontal(View child, int left, int dx) {
52 | return child.getLeft();
53 | }
54 |
55 | // 垂直方向边界进行控制
56 | @Override
57 | public int clampViewPositionVertical(View child, int top, int dy) {
58 | return clamp(top, 0, getMeasuredHeight());
59 | }
60 |
61 | // 手指释放的时候回调
62 | @Override
63 | public void onViewReleased(View releasedChild, float xvel, float yvel) {
64 | // mAutoBackView手指释放时可以自动回去
65 | if (releasedChild == mAutoBackView) {
66 | //调用settleCapturedViewAt回到某个位置,其内部调用mScroller.startScroll,因此重写computeScroll
67 | float newY = releasedChild.getY();
68 | if (newY <= DPIUtil.dip2px(releasedChild.getContext(), 80f)) {
69 | finalTop = mAutoBackOriginPos.y;
70 | mDragger.settleCapturedViewAt(mAutoBackOriginPos.x, mAutoBackOriginPos.y);
71 | } else {
72 | finalTop = ViewDragHelperLayout.this.getMeasuredHeight();
73 | mDragger.settleCapturedViewAt(0, ViewDragHelperLayout.this.getMeasuredHeight());
74 | }
75 | invalidate();
76 | }
77 | }
78 |
79 | //解决子View如果消耗事件就无法移动
80 | @Override
81 | public int getViewHorizontalDragRange(View child) {
82 | return 0;
83 | }
84 |
85 | @Override
86 | public int getViewVerticalDragRange(View child) {
87 | return getMeasuredHeight();
88 | }
89 |
90 | @Override
91 | public void onViewDragStateChanged(int state) {
92 | if (finalTop != -1 && mDragger.getViewDragState() == ViewDragHelper.STATE_IDLE) {
93 | if (finalTop == ViewDragHelperLayout.this.getMeasuredHeight()) {
94 | onClose();
95 | } else {
96 | onExpan();
97 | }
98 | finalTop = -1;
99 | }
100 | }
101 | });
102 | mDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_TOP);
103 | }
104 |
105 | // ViewDragHelper中拦截和处理事件时,需要会回调CallBack
106 | @Override
107 | public boolean onTouchEvent(MotionEvent event) {
108 | mDragger.processTouchEvent(event);
109 | return true;
110 | }
111 |
112 | @Override
113 | public void computeScroll() {
114 | if (mDragger.continueSettling(true)) {
115 | invalidate();
116 | }
117 | }
118 |
119 | @Override
120 | public boolean onInterceptTouchEvent(MotionEvent event) {
121 | return mDragger.shouldInterceptTouchEvent(event);
122 | }
123 |
124 | @Override
125 | protected void onLayout(boolean changed, int l, int t, int r, int b) {
126 | super.onLayout(changed, l, t, r, b);
127 | mAutoBackOriginPos.x = mAutoBackView.getLeft();
128 | mAutoBackOriginPos.y = mAutoBackView.getTop();
129 | }
130 |
131 | @Override
132 | protected void onSizeChanged(int w, int h, int oldw, int oldh) {
133 | super.onSizeChanged(w, h, oldw, oldh);
134 | }
135 |
136 | @Override
137 | protected void onFinishInflate() {
138 | super.onFinishInflate();
139 | mAutoBackView = getChildAt(0);
140 | }
141 |
142 |
143 | public OnExpandListenner getOnExpandListenner() {
144 | return onExpandListenner;
145 | }
146 |
147 | public void setOnExpandListenner(OnExpandListenner onExpandListenner) {
148 | this.onExpandListenner = onExpandListenner;
149 | }
150 |
151 | public void onExpan() {
152 | if (onExpandListenner != null) {
153 | isExpan = true;
154 | onExpandListenner.onExpan();
155 | }
156 | }
157 |
158 | public void onClose() {
159 | if (onExpandListenner != null) {
160 | isExpan = false;
161 | onExpandListenner.onClose();
162 | }
163 | }
164 |
165 | public boolean isExpan() {
166 | return isExpan;
167 | }
168 |
169 | public void setExpan(boolean expan) {
170 | isExpan = expan;
171 | }
172 |
173 | public boolean isNeedDrag() {
174 | return needDrag;
175 | }
176 |
177 | public void setNeedDrag(boolean needDrag) {
178 | this.needDrag = needDrag;
179 | }
180 |
181 | public interface OnExpandListenner {
182 | void onExpan();
183 |
184 | void onClose();
185 | }
186 |
187 | public static int clamp(int value, int min, int max) {
188 | if (value < min) {
189 | return min;
190 | } else if (value > max) {
191 | return max;
192 | }
193 | return value;
194 | }
195 | }
196 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## AppMethodTime
2 |
3 | 一个测量函数耗时的库(更新readme)
4 |
5 |
6 | >背景:这次没什么背景就是知识总结,Gradle自定义插件+Transform+javassist 做了个 JakeWharton大神hugo库类似的东西
7 |
8 | 特别说明:本文已经稍后送上的代码参考以及抄袭了(http://blog.csdn.net/eclipsexys/article/details/50973205)
9 | (https://github.com/HalfStackDeveloper/Savior),
10 | 还有巴掌大神的库(https://github.com/JeasonWong/CostTime) ,十分鸣谢巴掌大神手把手教我改代码
11 | (有用到代码的同学,联系我,有侵必删)
12 |
13 | 源码下载地址:(https://github.com/zjw-swun/AppMethodTime) 觉得有帮助可以给个star
14 |
15 | 简单介绍一下:Transform 参与class打包的Android
16 | gradle plugin的api,javassist 是生成或者修改class字节码的库。借由这2个特性,我们就可以完成类似于JakeWharton大神hugo库类似的东西。
17 |
18 | #1. 2种生成自定义插件的方式
19 | 1.新建一个BuildSrc module (lib module ,BuildSrc 名字固定),从src(包括src)开始以下文件或者文件夹都是自己建的(具体步骤就不讲了,CSDN 简书上都有讲)
20 | 
21 |
22 | 2.比第1种方式名字可以不固定,但是需要带上META那个文件夹,
23 |
24 | 
25 | 该build.gradle 需要加一个task
26 | ```
27 | //设置maven deployer
28 | uploadArchives {
29 | repositories {
30 | mavenDeployer {
31 | //设置插件的GAV参数
32 | pom.groupId = 'com.branch.plugin'
33 | pom.artifactId = 'dellog'
34 | pom.version = '1.0.0'
35 | //文件发布到下面目录
36 | repository(url: uri('../repo'))
37 | }
38 | }
39 | }
40 | ```
41 | 然后执行``uploadArchives`` 上传
42 | 具体不细说看代码吧
43 |
44 | 核心就是MyTransform类,以及MyInject类
45 | MyInject类里面的代码如下
46 | ```
47 | package com.zjw.plugin
48 |
49 | import javassist.*
50 |
51 | public class MyInject {
52 |
53 | private static ClassPool pool = ClassPool.getDefault()
54 | //注意这里需要替换你的anroid.jar路径
55 | static String androidJar = "D:\\Application\\Android\\sdkUpDate\\platforms\\android-24\\android.jar"
56 | static String myPackageName = "com.zjw.appmethodtime";
57 | static String myCostTimeAnnotation = "@com.zjw.appmethodtime.CostTime";
58 | static String CostTime = "CostTime";
59 |
60 | public static void injectDir(String path, String packageName, boolean enabeCostTime) {
61 | pool.appendClassPath(path)
62 | // 以下为windows环境下你的相应android.jar路径
63 | pool.insertClassPath(androidJar)
64 |
65 | println("enabeCostTime is " + enabeCostTime)
66 |
67 | File dir = new File(path)
68 | if (dir.isDirectory()) {
69 | dir.eachFileRecurse { File file ->
70 | String filePath = file.absolutePath
71 | //确保当前文件是class文件,并且不是系统自动生成的class文件以及注解文件
72 | if (filePath.endsWith(".class")
73 | && !filePath.contains('R$')
74 | && !filePath.contains('R.class')
75 | && !filePath.contains("BuildConfig.class")
76 | && !filePath.contains("CostTime")
77 | ) {
78 | // 判断当前目录是否是在我们的应用包里面
79 | int index = filePath.indexOf(packageName);
80 | boolean isMyPackage = index != -1;
81 | if (isMyPackage) {
82 | int end = filePath.length() - 6 // .class = 6
83 | String className = filePath.substring(index, end).replace('\\', '.').replace('/', '.')
84 | //开始修改class文件
85 | CtClass c = pool.getCtClass(className)
86 |
87 | if (c.isFrozen()) {
88 | c.defrost()
89 | }
90 | pool.importPackage(myPackageName)
91 |
92 | //给类添加计时变量
93 | CtField startTime = new CtField(CtClass.longType, "sStart", c);
94 | startTime.setModifiers(Modifier.STATIC);
95 | c.addField(startTime);
96 |
97 | //给类添加计时变量
98 | CtField endTime = new CtField(CtClass.longType, "sEnd", c);
99 | endTime.setModifiers(Modifier.STATIC);
100 | c.addField(endTime);
101 |
102 | //遍历类的所有方法
103 | CtMethod[] methods = c.getDeclaredMethods();
104 | for (CtMethod method : methods) {
105 | println("method ====" + method.longName)
106 | if (enabeCostTime
107 | && method.getAvailableAnnotations() != null
108 | && method.getAvailableAnnotations().length >= 1
109 | && "${method.getAvailableAnnotations()[0]}".contains(CostTime)
110 | ) {
111 | insertCostTimeCode(method)
112 | } else if (!enabeCostTime) {
113 | insertCostTimeCode(method)
114 | }
115 | }//END for (CtMethod method : methods)
116 | c.writeFile(path)
117 | c.detach()
118 | }//END if(isMyPackage)
119 | }
120 | }
121 | }
122 | }
123 |
124 | private static void insertCostTimeCode(CtMethod method) {
125 | //插入到函数第一句
126 | StringBuilder startInjectStr = new StringBuilder();
127 | startInjectStr.append("sStart = System.nanoTime();");
128 | print("方法第一句插入了:" + startInjectStr.toString() + "语句\n")
129 | method.insertBefore(startInjectStr.toString())
130 |
131 | //插入到函数最后一句
132 | StringBuilder endInjectStr = new StringBuilder();
133 | endInjectStr.append("sEnd = System.nanoTime();\n");
134 | endInjectStr.append("android.util.Log.e(\"AppMethodTime\",");
135 | endInjectStr.append("\"" + method.longName + "\"");
136 | endInjectStr.append("+(sEnd - sStart)/1000000+\" (毫秒)\");");
137 | print("方法最后一句插入了:" + endInjectStr.toString() + "语句\n")
138 | method.insertAfter(endInjectStr.toString(), true)
139 | }
140 | }
141 | ```
142 |
143 | #2. 插件自定义的配置字段
144 | ```
145 | pluginsrc{
146 | message = 'hello gradle plugin'
147 | cost = true
148 | }
149 | ```
150 | 在MyTransform类中
151 | ```
152 | MyInject.injectDir(directoryInput.file.absolutePath,
153 | "com" + File.separator + "zjw" + File.separator + "appmethodtime",
154 | project.pluginsrc.cost)
155 | ```
156 | 使用了。如果你想在自定义插件中自己创建的task中在你的app编译生成apk前读取
157 | ```
158 | pluginsrc{
159 | message = 'hello gradle plugin'
160 | cost = true
161 | }
162 | ```
163 | cost 等字段值的话,你得加上
164 | ``preBuild.dependsOn appPlugin``
165 |
166 | 不说了自定义插件的初级知识应该都在这里了
167 | 效果图
168 |
169 | 
170 | 说明:如果函数返回类型是void log中对应`` return is null ``
171 |
172 | # 2019/7/6 新增支持修改aar和jar 中class插入字节码
173 | 添加aarOrJarPath 配置字段,填入目标jar或者aar路径
174 | 执行gradle面板对应项目中other目录appMethodJarOrAar 任务即可在aarOrJarPath 配置的同目录下生成带 Target_前缀的目标jar或者aar文件
175 |
176 | # 2019/7/13 增加自定义lint
177 | 感谢 https://github.com/Omooo/CustomLint 的作者
178 |
179 | # 调试Gradle 插件的方法
180 | 1. 运行按钮 -> edit config -> 命名 + 指定要调试的源码位置 ->apply
181 | 2. studio 命令行中 : gradle assembleDebug -Dorg.gradle.debug=true --no-daemon
182 | 3. studio 面板debug启动 按钮
183 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjw/appmethodtime/EllipsizedTextView.java:
--------------------------------------------------------------------------------
1 | package com.zjw.appmethodtime;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.Context;
5 | import android.content.res.TypedArray;
6 | import android.graphics.Canvas;
7 | import androidx.annotation.Nullable;
8 | import androidx.core.content.ContextCompat;
9 | import android.text.Layout;
10 | import android.text.SpannableString;
11 | import android.text.Spanned;
12 | import android.text.StaticLayout;
13 | import android.text.TextPaint;
14 | import android.text.TextUtils;
15 | import android.text.method.LinkMovementMethod;
16 | import android.text.style.ClickableSpan;
17 | import android.text.style.ForegroundColorSpan;
18 | import android.util.AttributeSet;
19 | import android.view.View;
20 | import android.widget.TextView;
21 |
22 | /**
23 | * 在原textview 文案后添加$mFoldLine,如果遇到末尾放不下就变成 ...$mFoldLine 的组件
24 | */
25 | @SuppressLint("AppCompatCustomView")
26 | public class EllipsizedTextView extends TextView {
27 | private static int DEFAULT_TAIL_TEXT_COLOR;
28 | private static final String DEFAULT_ELLIPSIZE = "...";
29 | private String mUnFoldText;
30 | private String mEllipsizeText = DEFAULT_ELLIPSIZE;
31 | private static final String DEFAULT_UNFOLD_TEXT = " 查看详情>";
32 | private int mFoldLine;
33 | private int mTailColor;
34 | private String mFullText;
35 |
36 | // 绘制,防止重复进行绘制
37 | private boolean mHasDrawn = false;
38 |
39 | // 行间距倍数
40 | private float mLineSpacingMultiplier = 1.0f;
41 | // 行间距额外像素
42 | private float mLineSpacingExtra = 0.0f;
43 |
44 | public EllipsizedTextView(Context context) {
45 | this(context, null);
46 | }
47 |
48 | public EllipsizedTextView(Context context, @Nullable AttributeSet attrs) {
49 | this(context, attrs, 0);
50 | }
51 |
52 | public EllipsizedTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
53 | super(context, attrs, defStyleAttr);
54 | DEFAULT_TAIL_TEXT_COLOR = ContextCompat.getColor(context, R.color.c_4d97ff);
55 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
56 | mUnFoldText = a.getString(R.styleable.ExpandableTextView_unFoldText);
57 | if (null == mUnFoldText) {
58 | mUnFoldText = DEFAULT_UNFOLD_TEXT;
59 | }
60 | mFoldLine = a.getInt(R.styleable.ExpandableTextView_foldLine, getMaxLines());
61 | if (mFoldLine < 1) {
62 | mFoldLine = 1;
63 | }
64 | mTailColor = a.getColor(R.styleable.ExpandableTextView_tailTextColor, DEFAULT_TAIL_TEXT_COLOR);
65 | a.recycle();
66 | }
67 |
68 |
69 | @Override
70 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
71 | super.onMeasure(widthMeasureSpec, heightMeasureSpec);
72 | float availableScreenWidth = getMeasuredWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
73 | float availableTextWidth = availableScreenWidth * getMaxLines();
74 | CharSequence ellipsizedText = TextUtils.ellipsize(getText(), getPaint(), availableTextWidth, getEllipsize());
75 | if (getText().toString().equals(ellipsizedText.toString())) {
76 | //没有省略号的时候 预测量添加 查看详情 是否存在... 存在则加 ...查看详情> 否则就直接加就行
77 | String preText = getText() + DEFAULT_ELLIPSIZE + mUnFoldText;
78 | CharSequence preEllipsizeText = TextUtils.ellipsize(preText, getPaint(), availableTextWidth, getEllipsize());
79 | if (preText.equals(preEllipsizeText.toString())) {
80 | //直接加查看详情
81 | mEllipsizeText = "";
82 | } else {
83 | //如果之前预加字段导致end ellipseize的则还原字段
84 | if (mEllipsizeText.equals("")) {
85 | mEllipsizeText = DEFAULT_ELLIPSIZE;
86 | mHasDrawn = false;
87 | }
88 | mEllipsizeText = DEFAULT_ELLIPSIZE;
89 | }
90 | } else {
91 | if (mEllipsizeText.equals("")) {
92 | mEllipsizeText = DEFAULT_ELLIPSIZE;
93 | mHasDrawn = false;
94 | }
95 | }
96 | invalidate();
97 | }
98 |
99 | @Override
100 | public void setText(CharSequence text, BufferType type) {
101 | if (TextUtils.isEmpty(mFullText)) {
102 | mHasDrawn = false;
103 | mFullText = String.valueOf(text);
104 | }
105 | super.setText(text, type);
106 | }
107 |
108 |
109 | @Override
110 | protected void onDraw(Canvas canvas) {
111 | if (!mHasDrawn) {
112 | resetText();
113 | }
114 | super.onDraw(canvas);
115 | mHasDrawn = true;
116 | }
117 |
118 | public void setMaxLines(int maxLines) {
119 | super.setMaxLines(maxLines);
120 | mFoldLine = maxLines;
121 | }
122 |
123 | // 点击处理
124 | private ClickableSpan clickSpan = new ClickableSpan() {
125 | @Override
126 | public void onClick(View widget) {
127 | invalidate();
128 | }
129 |
130 | @Override
131 | public void updateDrawState(TextPaint ds) {
132 | ds.setColor(mTailColor);
133 | }
134 | };
135 |
136 | private ForegroundColorSpan mForegroundColorSpan;
137 |
138 | /**
139 | * 设置click span选择背景色
140 | * @param color
141 | */
142 | @Override
143 | public void setHighlightColor(int color) {
144 | super.setHighlightColor(color);
145 | }
146 |
147 | /**
148 | * 重置文字
149 | */
150 | private void resetText() {
151 | SpannableString spanStr = createFoldSpan(mFullText);
152 | setText(spanStr);
153 | setMovementMethod(LinkMovementMethod.getInstance());
154 | }
155 |
156 | public String getFullText() {
157 | return mFullText;
158 | }
159 |
160 | public void setFullText(String fullText) {
161 | mFullText = fullText;
162 | mHasDrawn = false;
163 | setText(fullText);
164 | invalidate();
165 | }
166 |
167 |
168 | /**
169 | * 创建收缩状态下的Span
170 | *
171 | * @param text
172 | * @return 收缩状态下的Span
173 | */
174 | private SpannableString createFoldSpan(String text) {
175 | String destStr = "";
176 | int start = 0;
177 | int end = 0;
178 | if (mEllipsizeText.equals("")){
179 | //不需要裁剪
180 | destStr = text + mUnFoldText;
181 | start = text.length();
182 | end = destStr.length();
183 | }else {
184 | //裁剪
185 | destStr = tailorText(text);
186 | start = destStr.length() - mUnFoldText.length();
187 | end = destStr.length();
188 | }
189 |
190 | SpannableString spanStr = new SpannableString(destStr);
191 | mForegroundColorSpan = new ForegroundColorSpan(mTailColor);
192 | spanStr.setSpan(mForegroundColorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
193 | return spanStr;
194 | }
195 |
196 | /**
197 | * 裁剪文本至固定行数(备用方法)
198 | *
199 | * @param text 源文本
200 | * @return 裁剪后的文本
201 | */
202 | private String tailorTextBackUp(String text) {
203 |
204 | String destStr = text + mEllipsizeText + mUnFoldText;
205 | Layout layout = makeTextLayout(destStr);
206 |
207 | // 如果行数大于固定行数
208 | if (layout.getLineCount() > getFoldLine()) {
209 | int index = layout.getLineEnd(getFoldLine() - 1);
210 | if (text.length() < index) {
211 | index = text.length();
212 | }
213 | // 从最后一位逐渐试错至固定行数(可以考虑用二分法改进)
214 | if (index <= 1) {
215 | return mEllipsizeText + mUnFoldText;
216 | }
217 | String subText = text.substring(0, index - 1);
218 | return tailorText(subText);
219 | } else {
220 | return destStr;
221 | }
222 | }
223 |
224 | /**
225 | * 裁剪文本至固定行数(二分法)。经试验,在文字长度不是很长时,效率比备用方法高不少;当文字长度过长时,备用方法则优势明显。
226 | *
227 | * @param text 源文本
228 | * @return 裁剪后的文本
229 | */
230 | private String tailorText(String text) {
231 | // return tailorTextBackUp(text);
232 |
233 | int start = 0;
234 | int end = text.length() - 1;
235 | int mid = (start + end) / 2;
236 | int find = finPos(text, mid);
237 | while (find != 0 && end > start) {
238 | if (find > 0) {
239 | end = mid - 1;
240 | } else if (find < 0) {
241 | start = mid + 1;
242 | }
243 | mid = (start + end) / 2;
244 | find = finPos(text, mid);
245 | }
246 |
247 | String ret;
248 | if (find == 0) {
249 | ret = text.substring(0, mid) + mEllipsizeText + mUnFoldText;
250 | } else {
251 | ret = tailorTextBackUp(text);
252 | }
253 | return ret;
254 | }
255 |
256 | /**
257 | * 查找一个位置P,到P时为mFoldLine这么多行,加上一个字符‘A’后则刚好为mFoldLine+1这么多行
258 | *
259 | * @param text 源文本
260 | * @param pos 位置
261 | * @return 查找结果
262 | */
263 | private int finPos(String text, int pos) {
264 | String destStr = text.substring(0, pos) + mEllipsizeText + mUnFoldText;
265 | Layout layout = makeTextLayout(destStr);
266 | Layout layoutMore = makeTextLayout(destStr + "A");
267 |
268 | int lineCount = layout.getLineCount();
269 | int lineCountMore = layoutMore.getLineCount();
270 |
271 | if (lineCount == getFoldLine() && (lineCountMore == getFoldLine() + 1)) {
272 | // 行数刚好到折叠行数
273 | return 0;
274 | } else if (lineCount > getFoldLine()) {
275 | // 行数比折叠行数多
276 | return 1;
277 | } else {
278 | // 行数比折叠行数少
279 | return -1;
280 | }
281 | }
282 |
283 | /**
284 | * 获取TextView的Layout,注意这里使用getWidth()得到宽度
285 | *
286 | * @param text 源文本
287 | * @return Layout
288 | */
289 | private Layout makeTextLayout(String text) {
290 | return new StaticLayout(text, getPaint(), getWidth() - getPaddingLeft() - getPaddingRight(), Layout.Alignment
291 | .ALIGN_NORMAL, mLineSpacingMultiplier, mLineSpacingExtra, true);
292 | }
293 |
294 |
295 | @Override
296 | public void setLineSpacing(float extra, float multiplier) {
297 | mLineSpacingExtra = extra;
298 | mLineSpacingMultiplier = multiplier;
299 | super.setLineSpacing(extra, multiplier);
300 | }
301 |
302 | public int getFoldLine() {
303 | return mFoldLine;
304 | }
305 | }
306 |
--------------------------------------------------------------------------------