我有很长的文字,我把这个文字分成了几页,但这是第一次显示,但第二次显示空白屏幕..
我已从此链接reference link
中获取代码
2.Problem
如果我将所有页面都刷到左侧,那么有时当我向右滑动时,这将不会滑动
为什么数据只是第一次显示而不是第二次显示...... 是否存在片段问题?
代码低于
{{myAttribut}}
TextPagerAdapter.class
public class FeedDetail extends Fragment {
View view;
Feeds feeds;
private ViewPager pagesView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.feed_detail, container, false);
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
bindViews();
}
private void bindViews() {
pagesView = (ViewPager) view.findViewById(R.id.pages);
Bundle bundle = getArguments();
if (bundle != null) {
feeds = (Feeds) bundle.getSerializable("data");
if (feeds != null) {
try {
pagesView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
PageSplitter pageSplitter = new PageSplitter(pagesView.getWidth(), pagesView.getHeight(), 1, 0);
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(getResources().getDimension(R.dimen.text_size));
pageSplitter.append(feeds.getDescription(), textPaint);
pagesView.setAdapter(new TextPagerAdapter(getActivity().getSupportFragmentManager(), pageSplitter.getPages()));
pagesView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
} catch (Exception e) {
Log.e("catch", e.toString());
}
}
}
}
PagerFragment class
public class TextPagerAdapter extends FragmentPagerAdapter {
private final List<CharSequence> pageTexts;
public TextPagerAdapter(FragmentManager fm, List<CharSequence> pageTexts) {
super(fm);
this.pageTexts = pageTexts;
}
@Override
public Fragment getItem(int i) {
return PageFragment.newInstance(pageTexts.get(i));
}
@Override
public int getCount() {
return pageTexts.size();
}
}
PageSplitter类
public class PageFragment extends Fragment {
private final static String PAGE_TEXT = "PAGE_TEXT";
public static PageFragment newInstance(CharSequence pageText) {
PageFragment frag = new PageFragment();
Bundle args = new Bundle();
args.putCharSequence(PAGE_TEXT, pageText);
frag.setArguments(args);
return frag;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
CharSequence text = getArguments().getCharSequence(PAGE_TEXT);
TextView pageView = (TextView) inflater.inflate(R.layout.page, container, false);
pageView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size));
pageView.setText(text);
return pageView;
}
**片段交易方法
public class PageSplitter {
private final int pageWidth;
private final int pageHeight;
private final float lineSpacingMultiplier;
private final int lineSpacingExtra;
private final List<CharSequence> pages = new ArrayList<CharSequence>();
private SpannableStringBuilder currentLine = new SpannableStringBuilder();
private SpannableStringBuilder currentPage = new SpannableStringBuilder();
private int currentLineHeight;
private int pageContentHeight;
private int currentLineWidth;
private int textLineHeight;
public PageSplitter(int pageWidth, int pageHeight, float lineSpacingMultiplier, int lineSpacingExtra) {
this.pageWidth = pageWidth;
this.pageHeight = pageHeight;
this.lineSpacingMultiplier = lineSpacingMultiplier;
this.lineSpacingExtra = lineSpacingExtra;
}
public void append(String text, TextPaint textPaint) {
textLineHeight = (int) Math.ceil(textPaint.getFontMetrics(null) * lineSpacingMultiplier + lineSpacingExtra);
String[] paragraphs = text.split("\n", -1);
int i;
for (i = 0; i < paragraphs.length - 1; i++) {
appendText(paragraphs[i], textPaint);
appendNewLine();
}
appendText(paragraphs[i], textPaint);
}
private void appendText(String text, TextPaint textPaint) {
String[] words = text.split(" ", -1);
int i;
for (i = 0; i < words.length - 1; i++) {
appendWord(words[i] + " ", textPaint);
}
appendWord(words[i], textPaint);
}
private void appendNewLine() {
currentLine.append("\n");
checkForPageEnd();
appendLineToPage(textLineHeight);
}
private void checkForPageEnd() {
if (pageContentHeight + currentLineHeight > pageHeight) {
pages.add(currentPage);
currentPage = new SpannableStringBuilder();
pageContentHeight = 0;
}
}
private void appendWord(String appendedText, TextPaint textPaint) {
int textWidth = (int) Math.ceil(textPaint.measureText(appendedText));
if (currentLineWidth + textWidth >= pageWidth) {
checkForPageEnd();
appendLineToPage(textLineHeight);
}
appendTextToLine(appendedText, textPaint, textWidth);
}
private void appendLineToPage(int textLineHeight) {
currentPage.append(currentLine);
pageContentHeight += currentLineHeight;
currentLine = new SpannableStringBuilder();
currentLineHeight = textLineHeight;
currentLineWidth = 0;
}
private void appendTextToLine(String appendedText, TextPaint textPaint, int textWidth) {
currentLineHeight = Math.max(currentLineHeight, textLineHeight);
currentLine.append(renderToSpannable(appendedText, textPaint));
currentLineWidth += textWidth;
}
public List<CharSequence> getPages() {
List<CharSequence> copyPages = new ArrayList<CharSequence>(pages);
SpannableStringBuilder lastPage = new SpannableStringBuilder(currentPage);
if (pageContentHeight + currentLineHeight > pageHeight) {
copyPages.add(lastPage);
lastPage = new SpannableStringBuilder();
}
lastPage.append(currentLine);
copyPages.add(lastPage);
return copyPages;
}
private SpannableString renderToSpannable(String text, TextPaint textPaint) {
SpannableString spannable = new SpannableString(text);
if (textPaint.isFakeBoldText()) {
spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, spannable.length(), 0);
}
return spannable;
}
答案 0 :(得分:1)
一些评论
我认为您不应该在另一个Thread中执行FragmentManager内容,因为所有与set Views相关的操作都需要在MainThread上处理。
您的PageSplitter不适合我,或者我可能不理解您的分裂概念。我以为你想用&#34; \ n&#34;分割整个文本。另外你想要应用一些TextPaint。也许详细说明你想要实现的目标。
工作示例
这个例子实现了一个简单的拆分,而不是你的PageSplitter,但我想你会明白我对你原来问题的建议。 SnapCenterListener只是一种水平捕捉到RecyclerView的某个项目的方法,可能有更高级的实现。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initRecycler();
}
private void initRecycler() {
RecyclerView recyclerView = findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.addOnScrollListener(new SnapCenterListener());
PageAdapter adapter = new PageAdapter(splitted());
recyclerView.setAdapter(adapter);
}
private List<String> splitted() {
String text = data();
List<String> split = new ArrayList<>(Arrays.asList(text.split("\n", -1)));
split.removeAll(Arrays.asList("", null));
return split;
}
public class PageAdapter extends RecyclerView.Adapter<PageAdapter.ViewHolder> {
private List<String> pages;
PageAdapter(List<String> pages) {
this.pages = pages;
}
@Override
public PageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
TextView v = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(pages.get(position));
}
@Override
public int getItemCount() {
return pages.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
ViewHolder(TextView v) {
super(v);
textView = v;
}
}
}
public class SnapCenterListener extends RecyclerView.OnScrollListener {
@Override
public void onScrollStateChanged(RecyclerView rv, int state) {
super.onScrollStateChanged(rv, state);
if (state != RecyclerView.SCROLL_STATE_IDLE) return;
LinearLayoutManager lm = (LinearLayoutManager) rv.getLayoutManager();
setScroll(rv, lm, lm.getOrientation() == LinearLayoutManager.HORIZONTAL);
}
private void setScroll(RecyclerView rv, LinearLayoutManager lm, boolean horizontal) {
int mid = (horizontal)? rv.getWidth() / 2 : rv.getHeight() / 2;
int minDistance = Integer.MAX_VALUE;
int position = 0;
int result = 0;
for (int i = lm.findFirstVisibleItemPosition(); i <= lm.findLastVisibleItemPosition(); i++) {
View view = lm.findViewByPosition(i);
int difference = getDiff(view, mid, horizontal);
int distance = Math.abs(difference);
if (distance < minDistance) {
minDistance = distance;
result = difference;
position = lm.getPosition(view);
}
}
if (position == 0 && result < 0 && result > -5) result = 0;
if (horizontal) rv.smoothScrollBy(result, 0);
else rv.smoothScrollBy(0, result);
}
private int getDiff(View v, int mid, boolean horizontal) {
return (horizontal)? (v.getLeft() + (v.getRight() - v.getLeft()) / 2) - mid :
(v.getTop() + (v.getBottom() - v.getTop()) / 2) - mid;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
}
private String data() {
return "What is Lorem Ipsum?\n" +
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
"\n" +
"Why do we use it?\n" +
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\n" +
"\n" +
"\n" +
"Where does it come from?\n" +
"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.\n" +
"\n" +
"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham." + "What is Lorem Ipsum?\\n\" +\n" +
" \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\\n\" +\n" +
" \"\\n\" +\n" +
" \"Why do we use it?\\n\" +\n" +
" \"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\\n\" +\n" +
" \"\\n\" +\n" +
" \"\\n\" +\n" +
" \"Where does it come from?\\n\" +\n" +
" \"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \\\"de Finibus Bonorum et Malorum\\\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \\\"Lorem ipsum dolor sit amet..\\\", comes from a line in section 1.10.32.\\n\" +\n" +
" \"\\n\" +\n" +
" \"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.Lorem ipsum dolor sit amet, sit nunc ornare primis, pede tempus nibh libero tortor sodales sed, purus maecenas, ad ornare in enim elit. Mauris metus vehicula luctus. Nisl lectus eu sollicitudin at, lectus rhoncus. Quia consectetuer lorem viverra. Quam malesuada non nunc diam phasellus. Ut aliquet aliquam arcu dolor arcu sit, adipiscing pede eget, arcu sit nullam. Eget congue malesuada ullamcorper dolor curabitur neque. Aliquam dignissim tortor dui, velit tempus sed quisque varius sed wisi. Nulla condimentum elit praesent quam. A potenti, nullam consequat libero massa vestibulum erat, dolor nulla nullam. Enim quis pede adipiscing ullamcorper sit. Mauris fusce mus nam dignissimos.\n" +
"Id justo magna vel. Fusce ridiculus cum imperdiet, sollicitudin malesuada aliquam mollit augue sollicitudin rhoncus, amet enim tincidunt id pede sociis ligula, in felis velit eu vulputate at integer. Ut vulputate orci magna laoreet torquent morbi, maecenas non quam convallis urna quis aliquam, id duis. Augue sit diam, dolor etiam nulla in eu. Et porta et quisque lacinia, non sed eu montes, pede scelerisque ligula. Eu non sit venenatis purus eleifend nec, est felis, consectetuer lorem hymenaeos, in sed magna nunc. Purus pretium. Condimentum felis, faucibus a diam sollicitudin. Quis erat iaculis, ac cras eget vitae pellentesque, phasellus vel sed eu etiam.\n" +
"Tempor egestas wisi dignissim, ac sapien ac vel velit nam, proin et lorem, quis felis pede lectus neque, donec magna nonummy nec posuere. Potenti eu felis nullam, dis purus, scelerisque eu orci. Turpis vehicula id, felis ullamcorper elementum in ut ipsum nonummy, ipsum interdum vehicula tellus viverra, enim vitae nulla massa quisque rutrum phasellus, id aut. Tempor viverra elementum massa sit euismod eget. Phasellus eros risus tempor a.\n" +
"Ipsum at et sem, nec litora ipsum, phasellus elit amet erat, sagittis aliquam. Lorem quisque justo erat sed, convallis sed sodales enim, feugiat egestas pretium dignissim ac in ornare. Ante at, turpis morbi, nunc integer augue feugiat quam, orci bibendum nibh in morbi. Eros convallis dis penatibus ipsum laoreet, fermentum nulla mattis nisl, luctus integer ut, fringilla mollis eget, eget fusce donec in. Erat lorem eleifend habitant eros euismod. Metus et justo libero suscipit faucibus, praesent iaculis urna. Purus montes porta et aenean quis vivamus, ut at non fermentum massa, sed lacinia enim, erat quisque. Commodo amet et porta eu et purus, congue elit taciti nisl parturient, vitae porttitor libero, sem rhoncus viverra morbi commodo vulputate, eleifend vivamus.\n" +
"+";
}
}
<强> activity_main.xml中强>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="nice.fontaine.pagesplitter.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
<强> my_text_view.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</TextView>
文字大小
<dimen name="text_size">14sp</dimen>