1

i have long text and i m separating this text into pages but for the first time it shows but second time it showing blank screen..

i have taken code from this link reference link

2.Problem

if i swiped all the pages to Left so sometimes when i swipe right this won't swipe

Why data only showing for the first time and not not thenAfter ...is this Fragment Proble?

codes are below

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());
                }

            }


        }

TextPagerAdapter.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();
}

}

PagerFragment class

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;
}

}

PageSplitter class

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;
}

**fragment transaction method

 public void changeFragment(final Fragment fragment, final String fragmenttag) {

    try {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
                fragmentTransaction.replace(R.id.fram, fragment, fragmenttag);
                fragmentTransaction.commit();
                fragmentTransaction.addToBackStack(null);
            }
        }, 50);
    } catch (Exception e) {

    }

}
Community
  • 1
  • 1
lizzy sam
  • 105
  • 1
  • 8
  • How many pages are we talking? The [docu](https://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html) of FragmentPagerAdapter says: "each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state." So it's maybe not the best choice for such a task... can't you maybe use a RecyclerView with horizontal scrolling instead? – Peppermint Paddy Nov 15 '17 at 20:43
  • @PeppermintPaddy And can u tell me y .... viewpager set content only once ,,,, because when i load **PageFragment** for the first time it showing data and ,,when i press back agian comes to **PageFragment** it shows balnk ??? what could be the reason behind? – lizzy sam Nov 16 '17 at 06:37
  • @PeppermintPaddy i tried with recyclerview ..but recyclerview set whole string in a single view with horizontal orientaion – lizzy sam Nov 16 '17 at 06:58
  • **Blank problem:** sound like it's related to a FragmentManager transition problem. Maybe you should use `replace` method instead of `add`.... but without seeing the code it's just a wild guess. **RecyclerView:** the Idea would be to split text first by screen size, right? Maybe you are not taking the right screen size params anymore. I'll try it myself and get back to you, when I have a solution ;) – Peppermint Paddy Nov 16 '17 at 07:25
  • @PeppermintPaddy it would be very Appreciated id u come with an Example Dear i Really tired of this problem,..... And i have used replace in Fragment Transaction ..I have Added code Edit – lizzy sam Nov 16 '17 at 07:43
  • @PeppermintPaddy i have made an demo project of above code ..it contains only three to four class ..... link is provided here https://www.dropbox.com/s/hnp83mgdlcpfa9m/pagesplitter-master.zip?dl=0 – lizzy sam Nov 16 '17 at 07:46
  • [Paginating text in Android](https://stackoverflow.com/a/32096884/3290339) – Onik May 23 '18 at 19:46

1 Answers1

1

Some remarks

  • I think you shouldn't do the FragmentManager stuff inside another Thread, because all operations related to set Views need to be handled on MainThread.

  • Your PageSplitter is not working for me or maybe I just don't understand the concept of your splitting. I thought you want to split a whole text by "\n" and additionally you want to apply some TextPaint. Maybe elaborate what you exactly want to achieve.

working example

This example implements a simple splitting instead of your PageSplitter but I think you get an idea what I proposed to your original question. The SnapCenterListener is just a approach to snap horizontally to a certain item of the RecyclerView, there are probably more advanced implementations.

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>

Text size

<dimen name="text_size">14sp</dimen>
Peppermint Paddy
  • 1,269
  • 9
  • 14
  • https://www.dropbox.com/s/0fw55w6pv1kohm2/1.jpg? https://www.dropbox.com/s/9iqfkol4flf560y/2.jpg?dl=0 see links for output ..... text not setting accroding to screen size – lizzy sam Nov 16 '17 at 17:03
  • but i got another example here is the link ... https://github.com/a-tolstykh/TextViewPagination/tree/master/app/src this link works but a problem is it does not return view count ..so can u help me to find count? – lizzy sam Nov 16 '17 at 17:31
  • As I said my example just shows you how to use the recyclerview not the pagination part, so it was more focused on answering your original question... in the github example you could pass the variable `mPageIndex` as a return value from `next()` and `previous()` method in PaginationController to the MainActivity and you'll get your count – Peppermint Paddy Nov 16 '17 at 21:41