├── .idea ├── .name └── copyright │ └── profiles_settings.xml ├── align-text-view-example ├── .gitignore ├── src │ └── main │ │ ├── res │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── values │ │ │ ├── dimen.xml │ │ │ ├── styles.xml │ │ │ ├── color.xml │ │ │ └── strings.xml │ │ ├── layout │ │ │ ├── activity_align_text_view_recycler_view.xml │ │ │ ├── activity_text_view_recycler_view_item.xml │ │ │ ├── activity_cb_align_text_view_recycler_view_item.xml │ │ │ ├── activity_align_text_view_recycler_view_item.xml │ │ │ ├── activity_align_text_view_npe_text.xml │ │ │ ├── activity_align_text_view_long_text.xml │ │ │ └── activity_align_text_view.xml │ │ └── drawable │ │ │ ├── blue_select.xml │ │ │ ├── red_select.xml │ │ │ └── green_select.xml │ │ ├── java │ │ └── me │ │ │ ├── codeboy │ │ │ └── android │ │ │ │ └── aligntextview │ │ │ │ └── example │ │ │ │ ├── vh │ │ │ │ ├── TextViewViewHolder.java │ │ │ │ ├── AlignTextViewViewHolder.java │ │ │ │ └── CBAlignTextViewViewHolder.java │ │ │ │ ├── AlignTextViewNpeExample.java │ │ │ │ ├── AlignTextViewRecyclerViewExample.java │ │ │ │ ├── TextViewRecyclerViewExample.java │ │ │ │ ├── CBAlignTextViewRecyclerViewExample.java │ │ │ │ ├── adpater │ │ │ │ ├── TextViewAdapter.java │ │ │ │ ├── AlignTextViewAdapter.java │ │ │ │ └── CBAlignTextViewAdapter.java │ │ │ │ ├── AlignTextViewExample.java │ │ │ │ └── AlignTextViewLongTextExample.java │ │ │ └── biubiubiu │ │ │ └── justifytext │ │ │ └── library │ │ │ └── JustifyTextView.java │ │ └── AndroidManifest.xml ├── proguard-rules.pro ├── build.gradle └── align-text-view-example.iml ├── gradle.properties ├── settings.gradle ├── screenshot.png ├── screenshot-small.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── align-text-view ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ ├── res │ │ └── values │ │ │ ├── aligntextview-styles.xml │ │ │ └── aligntextview_attr.xml │ │ └── java │ │ └── me │ │ └── codeboy │ │ └── android │ │ └── aligntextview │ │ ├── util │ │ └── CBAlignTextViewUtil.java │ │ ├── AlignTextView.java │ │ └── CBAlignTextView.java ├── lint.xml ├── build.gradle └── align-text-view.iml ├── .gitignore ├── AlignTextView.iml ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /.idea/.name: -------------------------------------------------------------------------------- 1 | AlignTextView -------------------------------------------------------------------------------- /align-text-view-example/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx3072M -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':align-text-view-example', 'align-text-view' -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androiddevelop/AlignTextView/HEAD/screenshot.png -------------------------------------------------------------------------------- /screenshot-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androiddevelop/AlignTextView/HEAD/screenshot-small.png -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androiddevelop/AlignTextView/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /align-text-view/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androiddevelop/AlignTextView/HEAD/align-text-view-example/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androiddevelop/AlignTextView/HEAD/align-text-view-example/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androiddevelop/AlignTextView/HEAD/align-text-view-example/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androiddevelop/AlignTextView/HEAD/align-text-view-example/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /align-text-view/lint.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/values/dimen.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 14sp 4 | 17sp 5 | 3dp 6 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Oct 15 10:57:02 CST 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/layout/activity_align_text_view_recycler_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | .apk 3 | *.ap_ 4 | 5 | # Files for the Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | .idea/ 13 | bin/ 14 | gen/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | gradle 20 | 21 | # Local configuration file (sdk path, etc) 22 | local.properties 23 | 24 | # Proguard folder generated by Eclipse 25 | proguard/ 26 | 27 | # Log Files 28 | *.log 29 | /target/ 30 | projectFilesBackup/ 31 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/values/color.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #dddddd 4 | #E51C23 5 | #F9BDBB 6 | #D2B48C 7 | #259B24 8 | #A3E9A4 9 | #76EEC6 10 | #4876FF 11 | #00BFFF 12 | #00BFFF 13 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/layout/activity_text_view_recycler_view_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 14 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/drawable/blue_select.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/drawable/red_select.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/drawable/green_select.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /align-text-view/src/main/res/values/aligntextview-styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 14 | 15 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AlignTextView 3 | TextView 4 | JustifyTextView 5 | AlignTextView 6 | CBAlignTextView 7 | 这是一段中英文混合的文本,I am very happy today测试TextView文本对齐AlignTextView可以通过setAlign()方法设置每一段尾行的对齐方式,默认尾行居左对齐.CBAlignTextView可以像原生TextView一样操作,但是需要使用getRealText()获取文本,欢迎访问open.codeboy.me 8 | 9 | 10 | -------------------------------------------------------------------------------- /align-text-view/src/main/res/values/aligntextview_attr.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/layout/activity_cb_align_text_view_recycler_view_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 14 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/layout/activity_align_text_view_recycler_view_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 15 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/vh/TextViewViewHolder.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example.vh; 2 | 3 | import android.support.v7.widget.RecyclerView; 4 | import android.view.View; 5 | import android.widget.TextView; 6 | 7 | import me.codeboy.android.aligntextview.example.R; 8 | 9 | /** 10 | * vh 11 | * Created by YD on 14/01/2018. 12 | */ 13 | 14 | public class TextViewViewHolder extends RecyclerView.ViewHolder { 15 | public TextView textView; 16 | 17 | public TextViewViewHolder(View itemView) { 18 | super(itemView); 19 | textView = (TextView) itemView.findViewById(R.id.text_view); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /align-text-view/src/main/java/me/codeboy/android/aligntextview/util/CBAlignTextViewUtil.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.util; 2 | 3 | /** 4 | * 文本工具 5 | * Created by yuedong.lyd on 11/30/15. 6 | */ 7 | public class CBAlignTextViewUtil { 8 | 9 | /** 10 | * 将中文标点替换为英文标点 11 | * 12 | * @param text 要替换的文本 13 | * @return 替换后的文本 14 | */ 15 | public static String replacePunctuation(String text) { 16 | text = text.replace(',', ',').replace('。', '.').replace('【', '[').replace('】', ']') 17 | .replace('?', '?').replace('!', '!').replace('(', '(').replace(')', ')').replace 18 | ('“', '"').replace('”', '"'); 19 | return text; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/vh/AlignTextViewViewHolder.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example.vh; 2 | 3 | import android.support.v7.widget.RecyclerView; 4 | import android.view.View; 5 | 6 | import me.codeboy.android.aligntextview.AlignTextView; 7 | import me.codeboy.android.aligntextview.example.R; 8 | 9 | /** 10 | * vh 11 | * Created by YD on 09/01/2017. 12 | */ 13 | 14 | public class AlignTextViewViewHolder extends RecyclerView.ViewHolder { 15 | public AlignTextView alignTextView; 16 | 17 | public AlignTextViewViewHolder(View itemView) { 18 | super(itemView); 19 | alignTextView = (AlignTextView) itemView.findViewById(R.id.align_text_view); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /align-text-view-example/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 /Users/YD/Software/android-sdk-macosx/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 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/vh/CBAlignTextViewViewHolder.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example.vh; 2 | 3 | import android.support.v7.widget.RecyclerView; 4 | import android.view.View; 5 | 6 | import me.codeboy.android.aligntextview.CBAlignTextView; 7 | import me.codeboy.android.aligntextview.example.R; 8 | 9 | /** 10 | * vh 11 | * Created by YD on 09/01/2017. 12 | */ 13 | 14 | public class CBAlignTextViewViewHolder extends RecyclerView.ViewHolder { 15 | public CBAlignTextView cbAlignTextView; 16 | 17 | public CBAlignTextViewViewHolder(View itemView) { 18 | super(itemView); 19 | cbAlignTextView = (CBAlignTextView) itemView.findViewById(R.id.cb_align_text_view); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/layout/activity_align_text_view_npe_text.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /AlignTextView.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /align-text-view-example/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion '25.0.2' 6 | 7 | defaultConfig { 8 | applicationId "me.codeboy.android.aligntextview.example" 9 | minSdkVersion 14 10 | targetSdkVersion 25 11 | versionCode 1 12 | versionName "1.0.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | 21 | sourceSets { 22 | main { 23 | jniLibs.srcDirs = ['libs'] 24 | } 25 | } 26 | compileOptions { 27 | sourceCompatibility JavaVersion.VERSION_1_7 28 | targetCompatibility JavaVersion.VERSION_1_7 29 | } 30 | } 31 | 32 | dependencies { 33 | compile fileTree(include: ['*.jar'], dir: 'libs') 34 | compile 'com.android.support:recyclerview-v7:25.1.0' 35 | compile 'com.android.support:appcompat-v7:25.1.0' 36 | // compile 'me.codeboy.android:align-text-view:2.3.0@aar' 37 | compile project (':align-text-view') 38 | compile 'me.codeboy.common:base:1.3.3' 39 | } 40 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/layout/activity_align_text_view_long_text.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 23 | 24 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/AlignTextViewNpeExample.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.os.Handler; 6 | import android.os.Message; 7 | import android.view.Window; 8 | 9 | import me.codeboy.android.aligntextview.CBAlignTextView; 10 | 11 | /** 12 | * AlignTextView 空指针 13 | * 14 | * @author yuedong.li 15 | */ 16 | public class AlignTextViewNpeExample extends Activity { 17 | 18 | private CBAlignTextView mTextViewTv; 19 | private String text = "这是一段中英文混合的文本,I am very happy today." + 20 | "测试TextView文本对齐\n\nAlignTextView可以通过setAlign()" + 21 | "方法设置每一段尾行的对齐方式,默认尾行居左对齐" + 22 | ".CBAlignTextView可以像原生TextView一样操作,但是需要使用getRealText()获取文本,欢迎访问open.codeboy.me"; 23 | 24 | @Override 25 | protected void onCreate(Bundle savedInstanceState) { 26 | super.onCreate(savedInstanceState); 27 | this.requestWindowFeature(Window.FEATURE_NO_TITLE); 28 | 29 | setContentView(R.layout.activity_align_text_view_npe_text); 30 | 31 | mTextViewTv = (CBAlignTextView) findViewById(R.id.align_text_view); 32 | mTextViewTv.setText(text); 33 | 34 | 35 | 36 | final Handler handler = new Handler() { 37 | @Override 38 | public void dispatchMessage(Message msg) { 39 | super.dispatchMessage(msg); 40 | mTextViewTv.setText(""); 41 | } 42 | }; 43 | 44 | new Thread() { 45 | public void run() { 46 | try { 47 | Thread.sleep(3000); 48 | handler.sendEmptyMessage(0); 49 | } catch (Exception e) { 50 | e.printStackTrace(); 51 | } 52 | } 53 | }.start(); 54 | 55 | } 56 | } -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/AlignTextViewRecyclerViewExample.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.support.v7.widget.LinearLayoutManager; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.view.Window; 8 | import android.view.WindowManager; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | import me.codeboy.android.aligntextview.example.adpater.AlignTextViewAdapter; 14 | 15 | /** 16 | * AlignTextView例子 recyclerView例子 17 | * 18 | * @author yuedong.li 19 | */ 20 | public class AlignTextViewRecyclerViewExample extends Activity { 21 | 22 | @Override 23 | protected void onCreate(Bundle savedInstanceState) { 24 | super.onCreate(savedInstanceState); 25 | this.requestWindowFeature(Window.FEATURE_NO_TITLE); 26 | this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager 27 | .LayoutParams.FLAG_FULLSCREEN); 28 | setContentView(R.layout.activity_align_text_view_recycler_view); 29 | 30 | final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); 31 | recyclerView.setLayoutManager(new LinearLayoutManager(this)); 32 | final AlignTextViewAdapter adapter = new AlignTextViewAdapter(this); 33 | List texts = new ArrayList<>(); 34 | for (int i = 0; i < 20; i++) { 35 | texts.add("欢迎访问codeboy.me,序号:" + i); 36 | } 37 | adapter.setData(texts); 38 | recyclerView.setAdapter(adapter); 39 | 40 | recyclerView.postDelayed(new Runnable() { 41 | @Override 42 | public void run() { 43 | List texts2 = new ArrayList<>(); 44 | for (int i = 20; i < 40; i++) { 45 | texts2.add("欢迎访问codeboy.me,序号:" + i); 46 | } 47 | adapter.appendData(texts2); 48 | adapter.notifyDataSetChanged(); 49 | } 50 | }, 5000); 51 | 52 | } 53 | } -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/TextViewRecyclerViewExample.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.support.v7.widget.LinearLayoutManager; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.view.Window; 8 | import android.view.WindowManager; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | import me.codeboy.android.aligntextview.example.adpater.TextViewAdapter; 14 | 15 | /** 16 | * AlignTextView例子 recyclerView例子 17 | * 18 | * @author yuedong.li 19 | */ 20 | public class TextViewRecyclerViewExample extends Activity { 21 | 22 | @Override 23 | protected void onCreate(Bundle savedInstanceState) { 24 | super.onCreate(savedInstanceState); 25 | this.requestWindowFeature(Window.FEATURE_NO_TITLE); 26 | this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager 27 | .LayoutParams.FLAG_FULLSCREEN); 28 | setContentView(R.layout.activity_align_text_view_recycler_view); 29 | 30 | final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); 31 | recyclerView.setLayoutManager(new LinearLayoutManager(this)); 32 | final TextViewAdapter adapter = new TextViewAdapter(this); 33 | List texts = new ArrayList<>(); 34 | for (int i = 0; i < 20; i++) { 35 | texts.add("欢迎访问codeboy.me,序号:" + i + "欢迎访问codeboy.me,序号:" + i + "欢迎访问codeboy.me,序号:" + i); 36 | } 37 | adapter.setData(texts); 38 | recyclerView.setAdapter(adapter); 39 | 40 | recyclerView.postDelayed(new Runnable() { 41 | @Override 42 | public void run() { 43 | List texts2 = new ArrayList<>(); 44 | for (int i = 20; i < 40; i++) { 45 | texts2.add("欢迎访问codeboy.me,序号:" + i); 46 | } 47 | adapter.appendData(texts2); 48 | adapter.notifyDataSetChanged(); 49 | } 50 | }, 100); 51 | 52 | } 53 | } -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/CBAlignTextViewRecyclerViewExample.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.support.v7.widget.LinearLayoutManager; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.view.Window; 8 | import android.view.WindowManager; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | import me.codeboy.android.aligntextview.example.adpater.CBAlignTextViewAdapter; 14 | 15 | /** 16 | * AlignTextView例子 recyclerView例子 17 | * 18 | * @author yuedong.li 19 | */ 20 | public class CBAlignTextViewRecyclerViewExample extends Activity { 21 | 22 | @Override 23 | protected void onCreate(Bundle savedInstanceState) { 24 | super.onCreate(savedInstanceState); 25 | this.requestWindowFeature(Window.FEATURE_NO_TITLE); 26 | this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager 27 | .LayoutParams.FLAG_FULLSCREEN); 28 | setContentView(R.layout.activity_align_text_view_recycler_view); 29 | 30 | final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); 31 | recyclerView.setLayoutManager(new LinearLayoutManager(this)); 32 | final CBAlignTextViewAdapter adapter = new CBAlignTextViewAdapter(this); 33 | List texts = new ArrayList<>(); 34 | for (int i = 0; i < 20; i++) { 35 | texts.add("欢迎访问codeboy.me,序号:" + i + "欢迎访问codeboy.me,序号:" + i + "欢迎访问codeboy.me,序号:" + i); 36 | } 37 | adapter.setData(texts); 38 | recyclerView.setAdapter(adapter); 39 | 40 | recyclerView.postDelayed(new Runnable() { 41 | @Override 42 | public void run() { 43 | List texts2 = new ArrayList<>(); 44 | for (int i = 20; i < 40; i++) { 45 | texts2.add("欢迎访问codeboy.me,序号:" + i); 46 | } 47 | adapter.appendData(texts2); 48 | adapter.notifyDataSetChanged(); 49 | } 50 | }, 100); 51 | 52 | } 53 | } -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/adpater/TextViewAdapter.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example.adpater; 2 | 3 | import android.content.Context; 4 | import android.support.v7.widget.RecyclerView; 5 | import android.text.TextUtils; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | import me.codeboy.android.aligntextview.example.R; 14 | import me.codeboy.android.aligntextview.example.vh.TextViewViewHolder; 15 | 16 | /** 17 | * adapter 18 | * Created by YD on 01/14/2018. 19 | */ 20 | public class TextViewAdapter extends RecyclerView.Adapter { 21 | private List mTexts = new ArrayList<>(); 22 | private Context mContext; 23 | 24 | public TextViewAdapter(Context context) { 25 | mContext = context; 26 | } 27 | 28 | /** 29 | * 设置数据 30 | * @param texts 文本 31 | */ 32 | public void setData(List texts) { 33 | if (texts == null || texts.size() == 0) { 34 | return; 35 | } 36 | mTexts.clear(); 37 | mTexts.addAll(texts); 38 | } 39 | 40 | /** 41 | * 追加数据 42 | * @param texts 文本 43 | */ 44 | public void appendData(List texts) { 45 | if (texts == null || texts.size() == 0) { 46 | return; 47 | } 48 | mTexts.addAll(texts); 49 | } 50 | 51 | @Override 52 | public TextViewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 53 | View rootView = LayoutInflater.from(mContext).inflate(R.layout.activity_text_view_recycler_view_item, parent, false); 54 | return new TextViewViewHolder(rootView); 55 | } 56 | 57 | @Override 58 | public void onBindViewHolder(TextViewViewHolder holder, int position) { 59 | String text = mTexts.get(position); 60 | if (!TextUtils.isEmpty(text)) { 61 | holder.textView.setText(mTexts.get(position)); 62 | } 63 | } 64 | 65 | @Override 66 | public int getItemCount() { 67 | return mTexts.size(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/adpater/AlignTextViewAdapter.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example.adpater; 2 | 3 | import android.content.Context; 4 | import android.support.v7.widget.RecyclerView; 5 | import android.text.TextUtils; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | import me.codeboy.android.aligntextview.example.R; 14 | import me.codeboy.android.aligntextview.example.vh.AlignTextViewViewHolder; 15 | 16 | /** 17 | * adapter 18 | * Created by YD on 09/01/2017. 19 | */ 20 | 21 | public class AlignTextViewAdapter extends RecyclerView.Adapter { 22 | private List mTexts = new ArrayList<>(); 23 | private Context mContext; 24 | 25 | public AlignTextViewAdapter(Context context) { 26 | mContext = context; 27 | } 28 | 29 | /** 30 | * 设置数据 31 | * @param texts 文本 32 | */ 33 | public void setData(List texts) { 34 | if (texts == null || texts.size() == 0) { 35 | return; 36 | } 37 | mTexts.clear(); 38 | mTexts.addAll(texts); 39 | } 40 | 41 | /** 42 | * 追加数据 43 | * @param texts 文本 44 | */ 45 | public void appendData(List texts) { 46 | if (texts == null || texts.size() == 0) { 47 | return; 48 | } 49 | mTexts.addAll(texts); 50 | } 51 | 52 | @Override 53 | public AlignTextViewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 54 | View rootView = LayoutInflater.from(mContext).inflate(R.layout.activity_align_text_view_recycler_view_item, parent, false); 55 | return new AlignTextViewViewHolder(rootView); 56 | } 57 | 58 | @Override 59 | public void onBindViewHolder(AlignTextViewViewHolder holder, int position) { 60 | String text = mTexts.get(position); 61 | if (!TextUtils.isEmpty(text)) { 62 | holder.alignTextView.setText(mTexts.get(position)); 63 | } 64 | } 65 | 66 | @Override 67 | public int getItemCount() { 68 | return mTexts.size(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/AlignTextViewExample.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.os.Handler; 6 | import android.text.method.ScrollingMovementMethod; 7 | import android.view.Window; 8 | import android.view.WindowManager; 9 | import android.widget.TextView; 10 | 11 | import me.codeboy.android.aligntextview.CBAlignTextView; 12 | 13 | /** 14 | * AlignTextView例子 15 | * 16 | * @author yuedong.li 17 | */ 18 | public class AlignTextViewExample extends Activity { 19 | 20 | private TextView mTextViewTv; 21 | private TextView mAlignTv; 22 | private TextView mJustifyTv; 23 | private CBAlignTextView mCbAlignTv; 24 | 25 | @Override 26 | protected void onCreate(Bundle savedInstanceState) { 27 | super.onCreate(savedInstanceState); 28 | this.requestWindowFeature(Window.FEATURE_NO_TITLE); 29 | this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager 30 | .LayoutParams.FLAG_FULLSCREEN); 31 | setContentView(R.layout.activity_align_text_view); 32 | 33 | mTextViewTv = (TextView) findViewById(R.id.text_view); 34 | mJustifyTv = (TextView) findViewById(R.id.justify_text_view); 35 | mAlignTv = (TextView) findViewById(R.id.align_text_view); 36 | mCbAlignTv = (CBAlignTextView) findViewById(R.id.cb_align_text_view); 37 | 38 | final String text = "这是一段中英文混合的文本,I am very happy today。 aaaaaaaaaa," + 39 | "测试TextView文本对齐\n\nAlignTextView可以通过setAlign()方法设置每一段尾行的对齐方式, 默认尾行居左对齐. " + 40 | "CBAlignTextView可以像原生TextView一样操作, 但是需要使用getRealText()获取文本, 欢迎访问open.codeboy.me"; 41 | mTextViewTv.setText(text); 42 | mJustifyTv.setText(text); 43 | mAlignTv.setText(text); 44 | // mCbAlignTv.setPunctuationConvert(true); 45 | mCbAlignTv.setText(text); 46 | 47 | mAlignTv.setMovementMethod(new ScrollingMovementMethod()); 48 | 49 | new Handler().postDelayed(new Runnable() { 50 | @Override 51 | public void run() { 52 | mAlignTv.setText(text + text + text); 53 | } 54 | }, 5000); 55 | 56 | } 57 | } -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/adpater/CBAlignTextViewAdapter.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example.adpater; 2 | 3 | import android.content.Context; 4 | import android.support.v7.widget.RecyclerView; 5 | import android.text.TextUtils; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | import me.codeboy.android.aligntextview.example.R; 14 | import me.codeboy.android.aligntextview.example.vh.CBAlignTextViewViewHolder; 15 | 16 | /** 17 | * adapter 18 | * Created by YD on 10/14/2017. 19 | */ 20 | public class CBAlignTextViewAdapter extends RecyclerView.Adapter { 21 | private List mTexts = new ArrayList<>(); 22 | private Context mContext; 23 | 24 | public CBAlignTextViewAdapter(Context context) { 25 | mContext = context; 26 | } 27 | 28 | /** 29 | * 设置数据 30 | * @param texts 文本 31 | */ 32 | public void setData(List texts) { 33 | if (texts == null || texts.size() == 0) { 34 | return; 35 | } 36 | mTexts.clear(); 37 | mTexts.addAll(texts); 38 | } 39 | 40 | /** 41 | * 追加数据 42 | * @param texts 文本 43 | */ 44 | public void appendData(List texts) { 45 | if (texts == null || texts.size() == 0) { 46 | return; 47 | } 48 | mTexts.addAll(texts); 49 | } 50 | 51 | @Override 52 | public CBAlignTextViewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 53 | View rootView = LayoutInflater.from(mContext).inflate(R.layout.activity_cb_align_text_view_recycler_view_item, parent, false); 54 | return new CBAlignTextViewViewHolder(rootView); 55 | } 56 | 57 | @Override 58 | public void onBindViewHolder(CBAlignTextViewViewHolder holder, int position) { 59 | String text = mTexts.get(position); 60 | if (!TextUtils.isEmpty(text)) { 61 | holder.cbAlignTextView.setPunctuationConvert(true); 62 | holder.cbAlignTextView.reset(); 63 | holder.cbAlignTextView.setText(mTexts.get(position)); 64 | } 65 | } 66 | 67 | @Override 68 | public int getItemCount() { 69 | return mTexts.size(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/codeboy/android/aligntextview/example/AlignTextViewLongTextExample.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview.example; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.os.Handler; 6 | import android.os.Message; 7 | import android.text.method.ScrollingMovementMethod; 8 | import android.view.Window; 9 | import android.widget.TextView; 10 | 11 | import me.codeboy.android.aligntextview.AlignTextView; 12 | 13 | /** 14 | * AlignTextView 长文本例子 15 | * 16 | * @author yuedong.li 17 | */ 18 | public class AlignTextViewLongTextExample extends Activity { 19 | 20 | private AlignTextView mTextViewTv; 21 | private TextView mTextViewTv2; 22 | private String text = "这是一段中英文混合的文本,I am very happy today." + 23 | "测试TextView文本对齐\n\nAlignTextView可以通过setAlign()" + 24 | "方法设置每一段尾行的对齐方式,默认尾行居左对齐" + 25 | ".CBAlignTextView可以像原生TextView一样操作,但是需要使用getRealText()获取文本,欢迎访问open.codeboy.me"; 26 | 27 | @Override 28 | protected void onCreate(Bundle savedInstanceState) { 29 | super.onCreate(savedInstanceState); 30 | this.requestWindowFeature(Window.FEATURE_NO_TITLE); 31 | 32 | setContentView(R.layout.activity_align_text_view_long_text); 33 | 34 | mTextViewTv = (AlignTextView) findViewById(R.id.align_text_view); 35 | mTextViewTv2 = (TextView) findViewById(R.id.text_view); 36 | 37 | mTextViewTv.setText(text); 38 | mTextViewTv2.setText(text); 39 | 40 | mTextViewTv.setMovementMethod(new ScrollingMovementMethod()); 41 | mTextViewTv2.setMovementMethod(new ScrollingMovementMethod()); 42 | 43 | 44 | final Handler handler = new Handler() { 45 | @Override 46 | public void dispatchMessage(Message msg) { 47 | super.dispatchMessage(msg); 48 | text = text + text; 49 | text = text + text; 50 | text = text + text; 51 | mTextViewTv.setText(text); 52 | mTextViewTv2.setText(text); 53 | } 54 | }; 55 | 56 | new Thread() { 57 | public void run() { 58 | try { 59 | Thread.sleep(3000); 60 | handler.sendEmptyMessage(0); 61 | } catch (Exception e) { 62 | e.printStackTrace(); 63 | } 64 | } 65 | }.start(); 66 | 67 | } 68 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /align-text-view/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.jfrog.bintray' 3 | apply plugin: 'com.github.dcendents.android-maven' 4 | android { 5 | compileSdkVersion 24 6 | buildToolsVersion '25.0.2' 7 | 8 | defaultConfig { 9 | minSdkVersion 14 10 | targetSdkVersion 25 11 | versionCode 3 12 | versionName "2.3.2" 13 | } 14 | 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 19 | } 20 | } 21 | compileOptions { 22 | sourceCompatibility JavaVersion.VERSION_1_7 23 | targetCompatibility JavaVersion.VERSION_1_7 24 | } 25 | } 26 | version = "2.3.2" 27 | def siteUrl = 'https://github.com/androiddevelop/AlignTextView' 28 | def gitUrl = 'https://github.com/androiddevelop/AlignTextView.git' 29 | group = "me.codeboy.android" 30 | archivesBaseName = "align-text-view" 31 | install { 32 | repositories.mavenInstaller { 33 | pom { 34 | project { 35 | packaging 'aar' 36 | name 'align-text-view' 37 | description 'Android Aligned Text View' 38 | url siteUrl 39 | licenses { 40 | license { 41 | name 'The Apache Software License, Version 2.0' 42 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 43 | } 44 | } 45 | developers { 46 | developer { 47 | id 'codeboy' 48 | name 'yuedong' 49 | email 'androiddevelop@qq.com' 50 | } 51 | } 52 | scm { 53 | connection gitUrl 54 | developerConnection gitUrl 55 | url siteUrl 56 | } 57 | } 58 | } 59 | } 60 | } 61 | task sourcesJar(type: Jar) { 62 | from android.sourceSets.main.java.srcDirs 63 | classifier = 'sources' 64 | } 65 | task javadoc(type: Javadoc) { 66 | source = android.sourceSets.main.java.srcDirs 67 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 68 | } 69 | task javadocJar(type: Jar, dependsOn: javadoc) { 70 | classifier = 'javadoc' 71 | from javadoc.destinationDir 72 | } 73 | artifacts { 74 | archives javadocJar 75 | archives sourcesJar 76 | } 77 | Properties properties = new Properties() 78 | properties.load(project.rootProject.file('local.properties').newDataInputStream()) 79 | bintray { 80 | user = properties.getProperty("bintray.user") 81 | key = properties.getProperty("bintray.apikey") 82 | configurations = ['archives'] 83 | pkg { 84 | repo = "maven" 85 | name = "AlignTextView" 86 | websiteUrl = siteUrl 87 | vcsUrl = gitUrl 88 | licenses = ["Apache-2.0"] 89 | publish = true 90 | version { 91 | gpg { 92 | sign = true 93 | passphrase = properties.getProperty("bintray.gpg.password") 94 | } 95 | mavenCentralSync { 96 | sync = true 97 | user = properties.getProperty("bintray.oss.user") 98 | password = properties.getProperty("bintray.oss.password") 99 | close = '1' 100 | } 101 | } 102 | } 103 | } 104 | dependencies { 105 | } -------------------------------------------------------------------------------- /align-text-view-example/src/main/java/me/biubiubiu/justifytext/library/JustifyTextView.java: -------------------------------------------------------------------------------- 1 | package me.biubiubiu.justifytext.library; 2 | 3 | import android.content.Context; 4 | import android.graphics.Canvas; 5 | import android.graphics.Paint; 6 | import android.text.Layout; 7 | import android.text.StaticLayout; 8 | import android.text.TextPaint; 9 | import android.util.AttributeSet; 10 | import android.widget.TextView; 11 | 12 | /** 13 | * @author ccheng 14 | * @Date 3/18/14 15 | */ 16 | public class JustifyTextView extends TextView { 17 | 18 | private int mLineY; 19 | private int mViewWidth; 20 | public static final String TWO_CHINESE_BLANK = " "; 21 | 22 | public JustifyTextView(Context context, AttributeSet attrs) { 23 | super(context, attrs); 24 | } 25 | 26 | @Override 27 | protected void onLayout(boolean changed, int left, int top, int right, 28 | int bottom) { 29 | super.onLayout(changed, left, top, right, bottom); 30 | } 31 | 32 | @Override 33 | protected void onDraw(Canvas canvas) { 34 | TextPaint paint = getPaint(); 35 | paint.setColor(getCurrentTextColor()); 36 | paint.drawableState = getDrawableState(); 37 | mViewWidth = getMeasuredWidth(); 38 | String text = getText().toString(); 39 | mLineY = 0; 40 | mLineY += getTextSize(); 41 | Layout layout = getLayout(); 42 | 43 | // layout.getLayout()在4.4.3出现NullPointerException 44 | if (layout == null) { 45 | return; 46 | } 47 | 48 | Paint.FontMetrics fm = paint.getFontMetrics(); 49 | 50 | int textHeight = (int) (Math.ceil(fm.descent - fm.ascent)); 51 | textHeight = (int) (textHeight * layout.getSpacingMultiplier() + layout 52 | .getSpacingAdd()); 53 | 54 | for (int i = 0; i < layout.getLineCount(); i++) { 55 | int lineStart = layout.getLineStart(i); 56 | int lineEnd = layout.getLineEnd(i); 57 | float width = StaticLayout.getDesiredWidth(text, lineStart, 58 | lineEnd, getPaint()); 59 | String line = text.substring(lineStart, lineEnd); 60 | if (needScale(line)) { 61 | drawScaledText(canvas, lineStart, line, width); 62 | } else { 63 | canvas.drawText(line, 0, mLineY, paint); 64 | } 65 | mLineY += textHeight; 66 | } 67 | } 68 | 69 | private void drawScaledText(Canvas canvas, int lineStart, String line, 70 | float lineWidth) { 71 | float x = 0; 72 | if (isFirstLineOfParagraph(lineStart, line)) { 73 | String blanks = " "; 74 | canvas.drawText(blanks, x, mLineY, getPaint()); 75 | float bw = StaticLayout.getDesiredWidth(blanks, getPaint()); 76 | x += bw; 77 | 78 | line = line.substring(3); 79 | } 80 | 81 | int gapCount = line.length() - 1; 82 | int i = 0; 83 | if (line.length() > 2 && line.charAt(0) == 12288 84 | && line.charAt(1) == 12288) { 85 | String substring = line.substring(0, 2); 86 | float cw = StaticLayout.getDesiredWidth(substring, getPaint()); 87 | canvas.drawText(substring, x, mLineY, getPaint()); 88 | x += cw; 89 | i += 2; 90 | } 91 | 92 | float d = (mViewWidth - lineWidth) / gapCount; 93 | for (; i < line.length(); i++) { 94 | String c = String.valueOf(line.charAt(i)); 95 | float cw = StaticLayout.getDesiredWidth(c, getPaint()); 96 | canvas.drawText(c, x, mLineY, getPaint()); 97 | x += cw + d; 98 | } 99 | } 100 | 101 | private boolean isFirstLineOfParagraph(int lineStart, String line) { 102 | return line.length() > 3 && line.charAt(0) == ' ' 103 | && line.charAt(1) == ' '; 104 | } 105 | 106 | private boolean needScale(String line) { 107 | if (line == null || line.length() == 0) { 108 | return false; 109 | } else { 110 | return line.charAt(line.length() - 1) != '\n'; 111 | } 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | AlignTextView 2 | --- 3 | #### **字体对齐的TextView** 4 | 5 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/me.codeboy.android/align-text-view/badge.svg)](https://maven-badges.herokuapp.com/maven-central/me.codeboy.android/align-text-view) 6 | 7 | ![截图](./screenshot-small.png) 8 | 9 | ## 系统要求 10 | Android 4.0以上 11 | 12 | ## 快速使用 13 | 14 | **build.gradle加入dependencies** 15 | 16 | compile 'me.codeboy.android:align-text-view:2.3.2' 17 | 18 | **AlignTextView (不支持选择复制,在不需要进行选择复制的情况下使用,排版效果好)** 19 | 20 | 24 | 25 | 26 | **CBAlignTextView (新的版本,支持选择复制,排版效果比较的好)** 27 | 28 | 33 | 34 | 35 | 如果需要支持android默认的选择复制,请在xml中加入以下代码: 36 | 37 | android:textIsSelectable="true" 38 | 39 | ## 相关方法 40 | 41 | #### 1.CBAlignTextView 42 | 43 | CBAlignTextView中增加了以下方法获取TextView的文本内容,请不要使用getText()获取 44 | 45 | ``` 46 | getRealText() 47 | ``` 48 | 由于Android L(5.0)之后对中文的版本进行了变化,造成不能由中文标点作为行首,所以为了能够使CBAlignTextView看起来更加工整,建议将中文符号用英文符号替换(默认不转换),可以通过以下三种方式转化 49 | 50 | - 使用转化函数转化标点符号: 51 | 52 | ``` 53 | CBAlignTextViewUtil.replacePunctuation(String text) 54 | ``` 55 | 56 | - 在设置CBAlignTextView文本前(setText),调用以下方法: 57 | 58 | ``` 59 | setPunctuationConvert(boolean convert) 60 | ``` 61 | 62 | - 如果需要多次设置文本,或者复用组件(如RecyclerView中),在后面每次设置文本前,请调用以下方法: 63 | 64 | ``` 65 | reset() 66 | ``` 67 | 68 | 69 | - 可以直接在xml布局中进行设置 70 | 71 | ``` 72 | 77 | 84 | 85 | ``` 86 | 87 | #### 2.AlignTextView 88 | AlignTextView是旧的版本,不支持选择复制,但是可以自定义最后一行的对齐方式 89 | 90 | ``` 91 | setAlign(Align align) 92 | ``` 93 | 94 | 设置每一段最后一行对齐方式,默认居左对齐,同时也可以在xml注释中设置对其方式: 95 | 96 | ``` 97 | 101 | 107 | 108 | ``` 109 | 110 | ## 使用说明 111 | 1. 不用进行选择复制的时候使用 `AlignTextView`,需要进行选择复制的时候使用`CBAlignTextView`。 112 | 2. `AlignTextView`与`CBAlignTextView`在对齐的时候不会对英文单词等进行考虑,它们都是以字符(character)为基础的,不是词(word)。 113 | 3. 使用CBAlignTextView时建议进行中文标点的转换。 114 | 4. demo项目位与app下,可以单独提取出me.codeboy.android.aligntextview.AlignTextView和me.codeboy.android.aligntextview.CBAlignTextView使用。 115 | 116 | ## 更新历史 117 | 118 | ### v2.3.2 119 | 1. 修复CBAlignTextView多次设置文本后空行的问题。 120 | 121 | ### v2.3.1 122 | 1. 修复CBAlignTextView在xml中设置text时空指针问题。 123 | 1. 修复CBAlignTextView设置空文本无效问题。 124 | 125 | ## License 126 | 127 | ``` 128 | Copyright 2016 Yuedong.li 129 | 130 | Licensed under the Apache License, Version 2.0 (the "License"); 131 | you may not use this file except in compliance with the License. 132 | You may obtain a copy of the License at 133 | 134 | http://www.apache.org/licenses/LICENSE-2.0 135 | 136 | Unless required by applicable law or agreed to in writing, software 137 | distributed under the License is distributed on an "AS IS" BASIS, 138 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 139 | See the License for the specific language governing permissions and 140 | limitations under the License. 141 | ``` 142 | 143 | > 有任何问题,欢迎发送邮件到app@codeboy.me交流. 144 | 145 | 146 | -------------------------------------------------------------------------------- /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 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /align-text-view-example/src/main/res/layout/activity_align_text_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 14 | 15 | 20 | 21 | 30 | 31 | 32 | 42 | 43 | 44 | 48 | 49 | 58 | 59 | 60 | 70 | 71 | 72 | 73 | 74 | 80 | 81 | 85 | 86 | 95 | 96 | 97 | 108 | 109 | 110 | 115 | 116 | 125 | 126 | 127 | 139 | 140 | 141 | 142 | -------------------------------------------------------------------------------- /align-text-view/align-text-view.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /align-text-view/src/main/java/me/codeboy/android/aligntextview/AlignTextView.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.graphics.Canvas; 6 | import android.graphics.Paint; 7 | import android.text.TextPaint; 8 | import android.util.AttributeSet; 9 | import android.util.TypedValue; 10 | import android.widget.TextView; 11 | 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | /** 16 | * 两端对齐的text view,可以设置最后一行靠左,靠右,居中对齐 17 | * 18 | * @author YD 19 | */ 20 | public class AlignTextView extends TextView { 21 | private float textHeight; // 单行文字高度 22 | private float textLineSpaceExtra = 0; // 额外的行间距 23 | private int width; // textView宽度 24 | private List lines = new ArrayList(); // 分割后的行 25 | private List tailLines = new ArrayList(); // 尾行 26 | private Align align = Align.ALIGN_LEFT; // 默认最后一行左对齐 27 | private boolean firstCalc = true; // 初始化计算 28 | 29 | private float lineSpacingMultiplier = 1.0f; 30 | private float lineSpacingAdd = 0.0f; 31 | 32 | private int originalHeight = 0; //原始高度 33 | private int originalLineCount = 0; //原始行数 34 | private int originalPaddingBottom = 0; //原始paddingBottom 35 | private boolean setPaddingFromMe = false; 36 | 37 | // 尾行对齐方式 38 | public enum Align { 39 | ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT // 居中,居左,居右,针对段落最后一行 40 | } 41 | 42 | public AlignTextView(Context context) { 43 | super(context); 44 | setTextIsSelectable(false); 45 | } 46 | 47 | public AlignTextView(Context context, AttributeSet attrs) { 48 | super(context, attrs); 49 | setTextIsSelectable(false); 50 | 51 | int[] attributes = new int[]{android.R.attr.lineSpacingExtra, android.R.attr.lineSpacingMultiplier}; 52 | TypedArray arr = context.obtainStyledAttributes(attrs, attributes); 53 | lineSpacingAdd = arr.getDimensionPixelSize(0, 0); 54 | lineSpacingMultiplier = arr.getFloat(1, 1.0f); 55 | originalPaddingBottom = getPaddingBottom(); 56 | arr.recycle(); 57 | 58 | TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AlignTextView); 59 | 60 | int alignStyle = ta.getInt(R.styleable.AlignTextView_align, 0); 61 | switch (alignStyle) { 62 | case 1: 63 | align = Align.ALIGN_CENTER; 64 | break; 65 | case 2: 66 | align = Align.ALIGN_RIGHT; 67 | break; 68 | default: 69 | align = Align.ALIGN_LEFT; 70 | break; 71 | } 72 | 73 | ta.recycle(); 74 | } 75 | 76 | 77 | @Override 78 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 79 | super.onLayout(changed, left, top, right, bottom); 80 | 81 | //首先进行高度调整 82 | if (firstCalc) { 83 | width = getMeasuredWidth(); 84 | String text = getText().toString(); 85 | TextPaint paint = getPaint(); 86 | lines.clear(); 87 | tailLines.clear(); 88 | 89 | // 文本含有换行符时,分割单独处理 90 | String[] items = text.split("\\n"); 91 | for (String item : items) { 92 | calc(paint, item); 93 | } 94 | 95 | //使用替代textview计算原始高度与行数 96 | measureTextViewHeight(text, paint.getTextSize(), getMeasuredWidth() - 97 | getPaddingLeft() - getPaddingRight()); 98 | 99 | //获取行高 100 | textHeight = 1.0f * originalHeight / originalLineCount; 101 | 102 | textLineSpaceExtra = textHeight * (lineSpacingMultiplier - 1) + lineSpacingAdd; 103 | 104 | //计算实际高度,加上多出的行的高度(一般是减少) 105 | int heightGap = (int) ((textLineSpaceExtra + textHeight) * (lines.size() - 106 | originalLineCount)); 107 | 108 | setPaddingFromMe = true; 109 | //调整textview的paddingBottom来缩小底部空白 110 | setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), 111 | originalPaddingBottom + heightGap); 112 | 113 | firstCalc = false; 114 | } 115 | } 116 | 117 | @Override 118 | protected void onDraw(Canvas canvas) { 119 | TextPaint paint = getPaint(); 120 | paint.setColor(getCurrentTextColor()); 121 | paint.drawableState = getDrawableState(); 122 | 123 | width = getMeasuredWidth(); 124 | 125 | Paint.FontMetrics fm = paint.getFontMetrics(); 126 | float firstHeight = getTextSize() - (fm.bottom - fm.descent + fm.ascent - fm.top); 127 | 128 | int gravity = getGravity(); 129 | if ((gravity & 0x1000) == 0) { // 是否垂直居中 130 | firstHeight = firstHeight + (textHeight - firstHeight) / 2; 131 | } 132 | 133 | int paddingTop = getPaddingTop(); 134 | int paddingLeft = getPaddingLeft(); 135 | int paddingRight = getPaddingRight(); 136 | width = width - paddingLeft - paddingRight; 137 | 138 | for (int i = 0; i < lines.size(); i++) { 139 | float drawY = i * textHeight + firstHeight; 140 | String line = lines.get(i); 141 | // 绘画起始x坐标 142 | float drawSpacingX = paddingLeft; 143 | float gap = (width - paint.measureText(line)); 144 | float interval = gap / (line.length() - 1); 145 | 146 | // 绘制最后一行 147 | if (tailLines.contains(i)) { 148 | interval = 0; 149 | if (align == Align.ALIGN_CENTER) { 150 | drawSpacingX += gap / 2; 151 | } else if (align == Align.ALIGN_RIGHT) { 152 | drawSpacingX += gap; 153 | } 154 | } 155 | 156 | for (int j = 0; j < line.length(); j++) { 157 | float drawX = paint.measureText(line.substring(0, j)) + interval * j; 158 | canvas.drawText(line.substring(j, j + 1), drawX + drawSpacingX, drawY + 159 | paddingTop + textLineSpaceExtra * i, paint); 160 | } 161 | } 162 | } 163 | 164 | /** 165 | * 设置尾行对齐方式 166 | * 167 | * @param align 对齐方式 168 | */ 169 | public void setAlign(Align align) { 170 | this.align = align; 171 | invalidate(); 172 | } 173 | 174 | /** 175 | * 计算每行应显示的文本数 176 | * 177 | * @param text 要计算的文本 178 | */ 179 | private void calc(Paint paint, String text) { 180 | if (text.length() == 0) { 181 | lines.add("\n"); 182 | return; 183 | } 184 | int startPosition = 0; // 起始位置 185 | float oneChineseWidth = paint.measureText("中"); 186 | int ignoreCalcLength = (int) (width / oneChineseWidth); // 忽略计算的长度 187 | StringBuilder sb = new StringBuilder(text.substring(0, Math.min(ignoreCalcLength + 1, 188 | text.length()))); 189 | 190 | for (int i = ignoreCalcLength + 1; i < text.length(); i++) { 191 | if (paint.measureText(text.substring(startPosition, i + 1)) > width) { 192 | startPosition = i; 193 | //将之前的字符串加入列表中 194 | lines.add(sb.toString()); 195 | 196 | sb = new StringBuilder(); 197 | 198 | //添加开始忽略的字符串,长度不足的话直接结束,否则继续 199 | if ((text.length() - startPosition) > ignoreCalcLength) { 200 | sb.append(text.substring(startPosition, startPosition + ignoreCalcLength)); 201 | } else { 202 | lines.add(text.substring(startPosition)); 203 | break; 204 | } 205 | 206 | i = i + ignoreCalcLength - 1; 207 | } else { 208 | sb.append(text.charAt(i)); 209 | } 210 | } 211 | if (sb.length() > 0) { 212 | lines.add(sb.toString()); 213 | } 214 | 215 | tailLines.add(lines.size() - 1); 216 | } 217 | 218 | 219 | @Override 220 | public void setText(CharSequence text, BufferType type) { 221 | firstCalc = true; 222 | super.setText(text, type); 223 | } 224 | 225 | @Override 226 | public void setPadding(int left, int top, int right, int bottom) { 227 | if (!setPaddingFromMe) { 228 | originalPaddingBottom = bottom; 229 | } 230 | setPaddingFromMe = false; 231 | super.setPadding(left, top, right, bottom); 232 | } 233 | 234 | 235 | /** 236 | * 获取文本实际所占高度,辅助用于计算行高,行数 237 | * 238 | * @param text 文本 239 | * @param textSize 字体大小 240 | * @param deviceWidth 屏幕宽度 241 | */ 242 | private void measureTextViewHeight(String text, float textSize, int deviceWidth) { 243 | TextView textView = new TextView(getContext()); 244 | textView.setText(text); 245 | textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); 246 | int widthMeasureSpec = MeasureSpec.makeMeasureSpec(deviceWidth, MeasureSpec.EXACTLY); 247 | int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); 248 | textView.measure(widthMeasureSpec, heightMeasureSpec); 249 | originalLineCount = textView.getLineCount(); 250 | originalHeight = textView.getMeasuredHeight(); 251 | } 252 | } -------------------------------------------------------------------------------- /align-text-view-example/align-text-view-example.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /align-text-view/src/main/java/me/codeboy/android/aligntextview/CBAlignTextView.java: -------------------------------------------------------------------------------- 1 | package me.codeboy.android.aligntextview; 2 | 3 | import android.content.ClipboardManager; 4 | import android.content.Context; 5 | import android.content.res.TypedArray; 6 | import android.graphics.Paint; 7 | import android.os.Build; 8 | import android.text.TextUtils; 9 | import android.util.AttributeSet; 10 | import android.util.Log; 11 | import android.widget.TextView; 12 | 13 | import java.lang.reflect.Method; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | import me.codeboy.android.aligntextview.util.CBAlignTextViewUtil; 18 | 19 | /** 20 | * 对齐的TextView 21 | *

22 | * 为了能够使TextView能够很好的进行排版,同时考虑到原生TextView中以word进行分割排版, 23 | * 那么我们可以将要换行的地方进行添加空格处理,这样就可以在合适的位置换行,同时也不会 24 | * 打乱原生的TextView的排版换行选择复制等问题。为了能够使右端尽可能的对齐,将右侧多出的空隙 25 | * 尽可能的分配到该行的标点后面。达到两段对齐的效果。 26 | *

27 | *

28 | * 重新设置文本前,请调用reset()进行状态重置。 29 | *

30 | * Created by yuedong.lyd on 6/28/15. 31 | */ 32 | public class CBAlignTextView extends TextView { 33 | private final static String TAG = CBAlignTextView.class.getSimpleName(); 34 | private final static char SPACE = ' '; //空格; 35 | private List addCharPosition = new ArrayList(); //增加空格的位置 36 | private static List punctuation = new ArrayList(); //标点符号 37 | private CharSequence oldText = ""; //旧文本,本来应该显示的文本 38 | private CharSequence newText = ""; //新文本,真正显示的文本 39 | private boolean inProcess = false; //旧文本是否已经处理为新文本 40 | private boolean isAddPadding = false; //是否添加过边距 41 | private boolean isConvert = false; //是否转换标点符号 42 | 43 | //标点符号用于在textview右侧多出空间时,将空间加到标点符号的后面,以便于右端对齐 44 | static { 45 | punctuation.clear(); 46 | punctuation.add(','); 47 | punctuation.add('.'); 48 | punctuation.add('?'); 49 | punctuation.add('!'); 50 | punctuation.add(';'); 51 | punctuation.add(','); 52 | punctuation.add('。'); 53 | punctuation.add('?'); 54 | punctuation.add('!'); 55 | punctuation.add(';'); 56 | punctuation.add(')'); 57 | punctuation.add('】'); 58 | punctuation.add(')'); 59 | punctuation.add(']'); 60 | punctuation.add('}'); 61 | } 62 | 63 | public CBAlignTextView(Context context) { 64 | super(context); 65 | } 66 | 67 | public CBAlignTextView(Context context, AttributeSet attrs) { 68 | super(context, attrs); 69 | TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CBAlignTextView); 70 | isConvert = ta.getBoolean(R.styleable.CBAlignTextView_punctuationConvert, false); 71 | ta.recycle(); 72 | 73 | //判断使用xml中是用android:text 74 | TypedArray tsa = context.obtainStyledAttributes(attrs, new int[]{ 75 | android.R.attr.text 76 | }); 77 | String text = tsa.getString(0); 78 | tsa.recycle(); 79 | if (!TextUtils.isEmpty(text)) { 80 | setText(text); 81 | } 82 | } 83 | 84 | /** 85 | * 监听文本复制,对于复制的文本进行空格剔除 86 | * 87 | * @param id 操作id(复制,全部选择等) 88 | * @return 是否操作成功 89 | */ 90 | @Override 91 | public boolean onTextContextMenuItem(int id) { 92 | if (id == android.R.id.copy) { 93 | 94 | if (isFocused()) { 95 | final int selStart = getSelectionStart(); 96 | final int selEnd = getSelectionEnd(); 97 | 98 | int min = Math.max(0, Math.min(selStart, selEnd)); 99 | int max = Math.max(0, Math.max(selStart, selEnd)); 100 | 101 | //利用反射获取选择的文本信息,同时关闭操作框 102 | try { 103 | Class cls = getClass().getSuperclass(); 104 | Method getSelectTextMethod = cls.getDeclaredMethod("getTransformedText", new 105 | Class[]{int.class, int.class}); 106 | getSelectTextMethod.setAccessible(true); 107 | CharSequence selectedText = (CharSequence) getSelectTextMethod.invoke(this, 108 | min, max); 109 | copy(selectedText.toString()); 110 | 111 | Method closeMenuMethod; 112 | if (Build.VERSION.SDK_INT < 23) { 113 | closeMenuMethod = cls.getDeclaredMethod("stopSelectionActionMode"); 114 | } else { 115 | closeMenuMethod = cls.getDeclaredMethod("stopTextActionMode"); 116 | } 117 | closeMenuMethod.setAccessible(true); 118 | closeMenuMethod.invoke(this); 119 | } catch (Exception e) { 120 | e.printStackTrace(); 121 | } 122 | } 123 | return true; 124 | } else { 125 | return super.onTextContextMenuItem(id); 126 | } 127 | } 128 | 129 | 130 | /** 131 | * 复制文本到剪切板,去除添加字符 132 | * 133 | * @param text 文本 134 | */ 135 | private void copy(String text) { 136 | ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context 137 | .CLIPBOARD_SERVICE); 138 | int start = newText.toString().indexOf(text); 139 | int end = start + text.length(); 140 | StringBuilder sb = new StringBuilder(text); 141 | for (int i = addCharPosition.size() - 1; i >= 0; i--) { 142 | int position = addCharPosition.get(i); 143 | if (position < end && position >= start) { 144 | sb.deleteCharAt(position - start); 145 | } 146 | } 147 | try { 148 | android.content.ClipData clip = android.content.ClipData.newPlainText(null, sb.toString()); 149 | clipboard.setPrimaryClip(clip); 150 | }catch (Exception e){ 151 | Log.e(TAG, e.getMessage()); 152 | } 153 | } 154 | 155 | /** 156 | * 重置状态 157 | */ 158 | public void reset(){ 159 | inProcess = false; 160 | addCharPosition.clear(); 161 | newText = ""; 162 | newText = ""; 163 | } 164 | 165 | /** 166 | * 处理多行文本 167 | * 168 | * @param paint 画笔 169 | * @param text 文本 170 | * @param width 最大可用宽度 171 | * @return 处理后的文本 172 | */ 173 | private String processText(Paint paint, String text, int width) { 174 | if (text == null || text.length() == 0) { 175 | return ""; 176 | } 177 | String[] lines = text.split("\\n"); 178 | StringBuilder newText = new StringBuilder(); 179 | for (String line : lines) { 180 | newText.append('\n'); 181 | newText.append(processLine(paint, line, width, newText.length() - 1)); 182 | } 183 | if (newText.length() > 0) { 184 | newText.deleteCharAt(0); 185 | } 186 | return newText.toString(); 187 | } 188 | 189 | 190 | /** 191 | * 处理单行文本 192 | * 193 | * @param paint 画笔 194 | * @param text 文本 195 | * @param width 最大可用宽度 196 | * @param addCharacterStartPosition 添加文本的起始位置 197 | * @return 处理后的文本 198 | */ 199 | private String processLine(Paint paint, String text, int width, int addCharacterStartPosition) { 200 | if (text == null || text.length() == 0) { 201 | return ""; 202 | } 203 | 204 | StringBuilder old = new StringBuilder(text); 205 | int startPosition = 0; // 起始位置 206 | 207 | float chineseWidth = paint.measureText("中"); 208 | float spaceWidth = paint.measureText(SPACE + ""); 209 | 210 | //最大可容纳的汉字,每一次从此位置向后推进计算 211 | int maxChineseCount = (int) (width / chineseWidth); 212 | 213 | //减少一个汉字宽度,保证每一行前后都有一个空格 214 | maxChineseCount--; 215 | 216 | //如果不能容纳汉字,直接返回空串 217 | if (maxChineseCount <= 0) { 218 | return ""; 219 | } 220 | 221 | for (int i = maxChineseCount; i < old.length(); i++) { 222 | if (paint.measureText(old.substring(startPosition, i + 1)) > (width - spaceWidth)) { 223 | 224 | //右侧多余空隙宽度 225 | float gap = (width - spaceWidth - paint.measureText(old.substring(startPosition, 226 | i))); 227 | 228 | List positions = new ArrayList(); 229 | for (int j = startPosition; j < i; j++) { 230 | char ch = old.charAt(j); 231 | if (punctuation.contains(ch)) { 232 | positions.add(j + 1); 233 | } 234 | } 235 | 236 | //空隙最多可以使用几个空格替换 237 | int number = (int) (gap / spaceWidth); 238 | 239 | //多增加的空格数量 240 | int use = 0; 241 | 242 | if (positions.size() > 0) { 243 | for (int k = 0; k < positions.size() && number > 0; k++) { 244 | int times = number / (positions.size() - k); 245 | int position = positions.get(k / positions.size()); 246 | for (int m = 0; m < times; m++) { 247 | old.insert(position + m, SPACE); 248 | addCharPosition.add(position + m + addCharacterStartPosition); 249 | use++; 250 | number--; 251 | } 252 | } 253 | } 254 | 255 | //指针移动,将段尾添加空格进行分行处理 256 | i = i + use; 257 | old.insert(i, SPACE); 258 | addCharPosition.add(i + addCharacterStartPosition); 259 | 260 | startPosition = i + 1; 261 | i = i + maxChineseCount; 262 | } 263 | } 264 | 265 | return old.toString(); 266 | } 267 | 268 | @Override 269 | public void setText(CharSequence text, BufferType type) { 270 | //父类初始化的时候子类暂时没有初始化, 覆盖方法会被执行,屏蔽掉 271 | if (addCharPosition == null) { 272 | super.setText(text, type); 273 | return; 274 | } 275 | if (!inProcess && (text != null && !text.equals(newText))) { 276 | oldText = text; 277 | process(false); 278 | super.setText(newText, type); 279 | } else { 280 | //恢复初始状态 281 | inProcess = false; 282 | super.setText(text, type); 283 | } 284 | } 285 | 286 | /** 287 | * 获取真正的text 288 | * 289 | * @return 返回text 290 | */ 291 | public CharSequence getRealText() { 292 | return oldText; 293 | } 294 | 295 | /** 296 | * 文本转化 297 | * 298 | * @param setText 是否设置textView的文本 299 | */ 300 | private void process(boolean setText) { 301 | if (oldText == null) { 302 | oldText = ""; 303 | } 304 | if (!inProcess && getVisibility() == VISIBLE) { 305 | addCharPosition.clear(); 306 | 307 | //转化字符,5.0系统对字体处理有所变动 308 | if (isConvert) { 309 | oldText = CBAlignTextViewUtil.replacePunctuation(oldText.toString()); 310 | } 311 | 312 | if (getWidth() == 0) { 313 | //没有测量完毕,等待测量完毕后处理 314 | post(new Runnable() { 315 | @Override 316 | public void run() { 317 | process(true); 318 | } 319 | }); 320 | return; 321 | } 322 | 323 | //添加过边距之后不再次添加 324 | if (!isAddPadding) { 325 | int spaceWidth = (int) (getPaint().measureText(SPACE + "")); 326 | newText = processText(getPaint(), oldText.toString(), getWidth() - getPaddingLeft 327 | () - 328 | getPaddingRight() - spaceWidth); 329 | setPadding(getPaddingLeft() + spaceWidth, getPaddingTop(), getPaddingRight(), 330 | getPaddingBottom()); 331 | isAddPadding = true; 332 | } else { 333 | newText = processText(getPaint(), oldText.toString(), getWidth() - getPaddingLeft 334 | () - 335 | getPaddingRight()); 336 | } 337 | inProcess = true; 338 | if (setText) { 339 | setText(newText); 340 | } 341 | } 342 | } 343 | 344 | /** 345 | * 是否转化标点符号,将中文标点转化为英文标点 346 | * 347 | * @param convert 是否转化 348 | */ 349 | public void setPunctuationConvert(boolean convert) { 350 | isConvert = convert; 351 | } 352 | } --------------------------------------------------------------------------------