本系列最终效果图如下:
本文实现的效果图如下:
长文本分页的场景是:在固定长宽(或是撑满屏幕)的TextView需要显示的长文本不能全部展现,同时又不想引入ScrollView的情形。其技术重点在于获取当前TextView所能容纳的行数和尾行最后一个字的指针(位置)。解决上述问题有两种技术路线:1、通过StaticLayout在View attach window 前获取行数和尾字指针。2、通过getLineBounds方法获取行高、getLineEnd方法获取行尾位置,在View attach window 后计算行数和尾字指针。
下面分别介绍两种方式的利弊:
StaticLayout是用来处理控件中静态文本的布局,其中的 getLineCount()、getLineBounds()、getLineEnd() 为在Attach window 前获取行数和尾字指针的关键函数。参考官方文档,其构造方法如下:
Builder for static layouts. The builder is the preferred pattern for constructing StaticLayout objects and should be preferred over the constructors, particularly to access newer features. To build a static layout, first call with the required arguments (text, paint, and width), then call setters for optional parameters, and finally to build the StaticLayout object. Parameters not explicitly set will get default values.
@RequiresApi(api = Build.VERSION_CODES.M)
private static StaticLayout getStaticLayout(TextView textView, int width) {
StaticLayout.Builder builder = StaticLayout.Builder.obtain(textView.getText(),
0, textView.getText().length(), textView.getPaint(), width)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.setTextDirection(TextDirectionHeuristics.FIRSTSTRONG_LTR)
.setLineSpacing(textView.getLineSpacingExtra(), textView.getLineSpacingMultiplier())
.setIncludePad(textView.getIncludeFontPadding())
.setBreakStrategy(textView.getBreakStrategy())
.setHyphenationFrequency(textView.getHyphenationFrequency())
.setMaxLines(textView.getMaxLines() == -1 ? Integer.MAX_VALUE : textView.getMaxLines());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setJustificationMode(textView.getJustificationMode());
}
if (textView.getEllipsize() != null && textView.getKeyListener() == null) {
builder.setEllipsize(textView.getEllipsize()).setEllipsizedWidth(width);
}
return builder.build();
}
由构造方法可知,构造StaticLayout必要的参数为一个已经设置了文本的TextView和TextView对应的固定宽度。下面给出获取当前TextView的分页结果的函数:
public static int getTextViewPages(TextView textView, int dp_width, int dp_height) {
StaticLayout staticLayout;
int width = dip2px(textView.getContext(),dp_width);
int height = dip2px(textView.getContext(),dp_height);
staticLayout = getStaticLayout(textView, width);
int lines_total = staticLayout.getLineCount();//总行数
int firstH=getLineHeight(0,staticLayout);
int otherH=getLineHeight(1,staticLayout);
int lines_in_page = (height - firstH) / otherH + 1;//能显示的行数
return lines_in_page/lines_total;//分页的页数
}
public static int getLineHeight(int line,StaticLayout view){
Rect rect=new Rect();
view.getLineBounds(line,rect);
return rect.bottom-rect.top;
}
函数中分别给出了获取:显示当前文本所需的总行数、当前TextView所能显示的行数、分页的页数三个参数的方法。由上面的函数可知,除了构造StaticLayout必要的TextView、固定宽度以外还需要TextView的固定高度来计算当前界面所能显示的行数。
这里我们就能看出方法一的弊端:需要事先给出TextView的宽高,若布局变动,则需要同步更改对应的宽高。
注意:这里的TextView的宽高不能设置为wrap_content,且通过方法textView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)测量的宽高亦不准确,只能通过设置固定值,或 match_parents时通过获取屏幕宽高得到。
为保证分页的灵活性和适应性,本文选择采用第二种方式实现:
上文提到,在View绘制前调用textView.measure方法测量的结果并不准确,于是就需要保证View 绘制后(Attach window后)再获取View的宽高。这里就要用到View.post方法,该方法中传入的Runnable一定在Attach window后被执行。
r = () -> {
pages = new ArrayList<>();
pages = PageSplit.getPage(test_content, "", tv_page);
System.out.println("pages:"+pages.size());
tv_page.setText(pages.get(current_page).getPage_content());
};
tv_page.post(r);
其中关键的方法就是PageSplit.getPage,它的思路与第一种方法一致,下面给出它的实现过程:
public class NovelContentPage {
private int start_pos;
private int end_pos;
private int page_id;
private String page_content;
private boolean isFirstPage;//当前页是否属于本章的首页
private String title;//首页所包含的标题,仅在isFirstPage = true 时适用
public int getStart_pos() {
return start_pos;
}
public void setStart_pos(int start_pos) {
this.start_pos = start_pos;
}
public int getEnd_pos() {
return end_pos;
}
public void setEnd_pos(int end_pos) {
this.end_pos = end_pos;
}
public int getPage_id() {
return page_id;
}
public void setPage_id(int page_id) {
this.page_id = page_id;
}
public String getPage_content() {
return page_content;
}
public void setPage_content(String page_content) {
this.page_content = page_content;
}
public boolean isFirstPage() {
return isFirstPage;
}
public void setFirstPage(boolean firstPage) {
isFirstPage = firstPage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return page_content;
}
}
public static int getPageLineCount(TextView view){
/*
* The first row's height is different from other row.
*/
int h = view.getBottom() - view.getTop();
int firstH=getLineHeight(0,view);
int otherH=getLineHeight(1,view);
int lines = 1;
if (otherH!=0)lines = (h-firstH)/otherH + 1;//仅一行时返回1
return lines;
}
//获取某一行的行高
public static int getLineHeight(int line,TextView view){
Rect rect=new Rect();
view.getLineBounds(line,rect);
return rect.bottom-rect.top;
}
public static ArrayList<NovelContentPage> getPage(@NonNull String mContent, String title, TextView textView){
textView.setText(mContent);
int count=textView.getLineCount();
int pCount=getPageLineCount(textView);
int pageNum = (int) Math.ceil((double) ((double) count/(double) pCount));
ArrayList<NovelContentPage> pages = new ArrayList<>();
for(int i=0;i < pageNum;i++){
NovelContentPage current_page = new NovelContentPage();
int end_pos = mContent.length();
int start_pos = 0;
if (i!=0)start_pos = pages.get(i-1).getEnd_pos();
if (i!=pageNum-1)end_pos = textView.getLayout().getLineEnd((i+1)*pCount-1);
current_page.setStart_pos(start_pos);
current_page.setEnd_pos(end_pos);
current_page.setPage_id(i);
if (i==0){
current_page.setFirstPage(true);
current_page.setTitle(title);
}
current_page.setPage_content(mContent.substring(start_pos,end_pos));
pages.add(current_page);
}
return pages;
}
在显示时,先将长文本直接设置到TextView,在通过post方法进行分页,分页后再将第一页重新赋值到TextView中。该过程在用户视觉上不会有闪烁,非常流畅。方法二在运行时的性能上弱于方法一,但在灵活性上大大胜过。
为了统一变量,不再区分长文本和分页后的文本,可以将长文本视为一个临时的页,于是在class NovelContentPage中引入变量 isTempPage:
private boolean isTempPage;//是否是还未分页的临时页
public void setTempPage(boolean tempPage) {
isTempPage = tempPage;
}
public int getBelong_to_chapID() {
return belong_to_chapID;
}
getPage也需要作变形:
public static ArrayList<NovelContentPage> getPage(@NonNull NovelContentPage tempPage, TextView textView){
String mContent = tempPage.getPage_content();
textView.setText(mContent);
int count=textView.getLineCount();
int pCount=getPageLineCount(textView);
int pageNum = (int) Math.ceil((double) ((double) count/(double) pCount));
ArrayList<NovelContentPage> pages = new ArrayList<>();
for(int i=0;i < pageNum;i++){
NovelContentPage current_page = new NovelContentPage();
int end_pos = mContent.length();
int start_pos = 0;
if (i!=0)start_pos = pages.get(i-1).getEnd_pos();
if (i!=pageNum-1)end_pos = textView.getLayout().getLineEnd((i+1)*pCount-1);
current_page.setStart_pos(start_pos);
current_page.setEnd_pos(end_pos);
current_page.setPage_id(i);
if (i==0){
current_page.setFirstPage(true);
current_page.setTitle(tempPage.getTitle());
}
current_page.setPage_content(mContent.substring(start_pos,end_pos));
current_page.setTempPage(false);
pages.add(current_page);
}
return pages;
}
在第三章中,我将结合一二两章的内容,阐述如何在ViewPager2的Adapter中应用本文所述的分页方法,并重点讲解如何在翻页过程中动态添加页面及章节。