Example usage for android.widget TextView getLineCount

List of usage examples for android.widget TextView getLineCount

Introduction

In this page you can find the example usage for android.widget TextView getLineCount.

Prototype

public int getLineCount() 

Source Link

Document

Return the number of lines of text, or 0 if the internal Layout has not been built.

Usage

From source file:Main.java

public static String getEllipsisedText(TextView textView) {
    try {//from  w w  w .  j  av a  2  s .  c om
        String text = textView.getText().toString();
        int lines = textView.getLineCount();
        int width = textView.getWidth();
        int len = text.length();

        Log.d("Test", "text-->" + text + "; lines-->" + lines + "; width-->" + width + ";len-->" + len);
        TextUtils.TruncateAt where = TextUtils.TruncateAt.END;
        TextPaint paint = textView.getPaint();

        StringBuffer result = new StringBuffer();

        int spos = 0, cnt, tmp, hasLines = 0;

        while (hasLines < lines - 1) {
            cnt = paint.breakText(text, spos, len, true, width, null);
            if (cnt >= len - spos) {
                result.append(text.substring(spos));
                break;
            }

            tmp = text.lastIndexOf('\n', spos + cnt - 1);

            if (tmp >= 0 && tmp < spos + cnt) {
                result.append(text.substring(spos, tmp + 1));
                spos += tmp + 1;
            } else {
                tmp = text.lastIndexOf(' ', spos + cnt - 1);
                if (tmp >= spos) {
                    result.append(text.substring(spos, tmp + 1));
                    spos += tmp + 1;
                } else {
                    result.append(text.substring(spos, cnt));
                    spos += cnt;
                }
            }

            hasLines++;
        }

        if (spos < len) {
            result.append(TextUtils.ellipsize(text.subSequence(spos, len), paint, (float) width, where));
        }

        return result.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.findme.views.ExpandableTextView.java

private static int getRealTextViewHeight(TextView textView) {
    int textHeight = textView.getLayout().getLineTop(textView.getLineCount());
    int padding = textView.getCompoundPaddingTop() + textView.getCompoundPaddingBottom();
    return textHeight + padding;
}

From source file:com.rashwan.reactive_popular_movies.common.utilities.ExpandableTextView.java

private static int getRealTextViewHeight(@NonNull TextView textView, int parentPadding) {
    int textHeight = textView.getLayout().getLineTop(textView.getLineCount());
    int padding = textView.getCompoundPaddingTop() + textView.getCompoundPaddingBottom();
    return textHeight + padding + parentPadding;
}

From source file:com.arksh.summer.ui.zone.widget.ExpandableTextView.java

/**
 * ?tv?padding/*  w w w.  j a  v a2  s  . c  om*/
 * @param textView
 * @return
 */
private static int getRealTextViewHeight(TextView textView) {
    int textHeight = textView.getLayout().getLineTop(textView.getLineCount());
    int padding = textView.getCompoundPaddingTop() + textView.getCompoundPaddingBottom();
    return textHeight + padding;
}

From source file:com.desno365.mods.DesnoUtils.java

public static void collapseTextView(ViewGroup container, final TextView tv, int collapsedHeight) {

    if (Build.VERSION.SDK_INT >= 19) {
        int lines = tv.getLineCount();

        // animation
        TransitionManager.beginDelayedTransition(container, new AutoTransition()
                .setDuration(SharedConstants.CHANGELOG_TEXT_ANIMATION_DURATION_PER_LINE * lines));

        // collapse the view by setting the collapsed height
        DesnoUtils.setViewHeight(tv, collapsedHeight);

        // restore initial state of the TextView when the animation finishes
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override//  w  w  w  .  j ava2  s.  c  om
            public void run() {
                DesnoUtils.setViewHeight(tv, ViewGroup.LayoutParams.WRAP_CONTENT);
                tv.setMaxLines(SharedConstants.CHANGELOG_TEXT_MAX_LINES);
            }
        }, SharedConstants.CHANGELOG_TEXT_ANIMATION_DURATION_PER_LINE * lines + 100);
    } else {
        // no animation without the new APIs :/
        tv.setMaxLines(SharedConstants.CHANGELOG_TEXT_MAX_LINES);
    }

}

From source file:com.desno365.mods.DesnoUtils.java

public static void expandTextView(ViewGroup container, TextView tv) {
    // animation// w  w w .j a  va2 s  . c  o  m
    if (Build.VERSION.SDK_INT >= 19) {
        TransitionManager.beginDelayedTransition(container, new AutoTransition()
                .setDuration(SharedConstants.CHANGELOG_TEXT_ANIMATION_DURATION_PER_LINE * tv.getLineCount()));
    }

    // expand the TextView with setMaxLines
    tv.setMaxLines(Integer.MAX_VALUE);
}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

public void statusUpdate(String msg) {
    TextView tv = (TextView) MyApp.context.findViewById(R.id.textview);
    tv.append(msg);/*from   w ww  .  jav a  2 s.c  o  m*/

    try {
        int lineTop = 0;
        try {
            lineTop = tv.getLayout().getLineTop(tv.getLineCount());
        } catch (Throwable e) {
            lineTop = 0;
        }

        final int scrollAmount = lineTop - tv.getHeight();

        if (scrollAmount > 0) {
            tv.scrollTo(0, scrollAmount);
        } else {
            tv.scrollTo(0, 0);
        }

    } catch (Throwable e) {
        Log.i(MyApp.TAG, e.getMessage().toString());
    }
}

From source file:de.baumann.hhsmoodle.data_count.Count_Fragment.java

public void setCountList() {

    if (isFABOpen) {
        closeFABMenu();/*  w  w w . j  a va2  s  .com*/
    }

    //display data
    final int layoutstyle = R.layout.list_item_notes;
    int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes };
    String[] column = new String[] { "count_title", "count_content", "count_creation" };
    final Cursor row = db.fetchAllData(getActivity());
    adapter = new SimpleCursorAdapter(getActivity(), layoutstyle, row, column, xml_id, 0) {
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String count_title = row2.getString(row2.getColumnIndexOrThrow("count_title"));
            final String count_content = row2.getString(row2.getColumnIndexOrThrow("count_content"));
            final String count_icon = row2.getString(row2.getColumnIndexOrThrow("count_icon"));
            final String count_attachment = row2.getString(row2.getColumnIndexOrThrow("count_attachment"));
            final String count_creation = row2.getString(row2.getColumnIndexOrThrow("count_creation"));

            View v = super.getView(position, convertView, parent);
            final TextView tv = (TextView) v.findViewById(R.id.text);

            if (count_attachment.isEmpty()) {

                tv.setText(count_content);

                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        int n = tv.getLineCount();

                        StringBuilder sb = new StringBuilder(n);
                        for (int i = 0; i < n; ++i) {
                            sb.append("0" + '\n');
                        }
                        String result = sb.toString();

                        db.update(Integer.parseInt(_id), count_title, count_content, count_icon, result,
                                count_creation);
                        setCountList();
                    }
                }, 500);
            }

            ImageView iv_icon = (ImageView) v.findViewById(R.id.icon_notes);
            helper_main.switchIcon(getActivity(), count_icon, "count_icon", iv_icon);

            iv_icon.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    final helper_main.Item[] items = {
                            new helper_main.Item(getString(R.string.note_priority_0), R.drawable.circle_green),
                            new helper_main.Item(getString(R.string.note_priority_1), R.drawable.circle_yellow),
                            new helper_main.Item(getString(R.string.note_priority_2), R.drawable.circle_red), };

                    ListAdapter adapter = new ArrayAdapter<helper_main.Item>(getActivity(),
                            android.R.layout.select_dialog_item, android.R.id.text1, items) {
                        @NonNull
                        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                            //Use super class to create the View
                            View v = super.getView(position, convertView, parent);
                            TextView tv = (TextView) v.findViewById(android.R.id.text1);
                            tv.setTextSize(18);
                            tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0);
                            //Add margin between image and text (support various screen densities)
                            int dp5 = (int) (24 * getResources().getDisplayMetrics().density + 0.5f);
                            tv.setCompoundDrawablePadding(dp5);

                            return v;
                        }
                    };

                    new AlertDialog.Builder(getActivity())
                            .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int whichButton) {
                                    dialog.cancel();
                                }
                            }).setAdapter(adapter, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int item) {
                                    if (item == 0) {
                                        db.update(Integer.parseInt(_id), count_title, count_content, "3",
                                                count_attachment, count_creation);
                                        setCountList();
                                    } else if (item == 1) {
                                        db.update(Integer.parseInt(_id), count_title, count_content, "2",
                                                count_attachment, count_creation);
                                        setCountList();
                                    } else if (item == 2) {
                                        db.update(Integer.parseInt(_id), count_title, count_content, "1",
                                                count_attachment, count_creation);
                                        setCountList();
                                    }
                                }
                            }).show();
                }
            });
            return v;
        }
    };

    //display data by filter
    final String note_search = sharedPref.getString("filter_countBY", "note_title");
    sharedPref.edit().putString("filter_countBY", "note_title").apply();
    filter.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return db.fetchDataByFilter(constraint.toString(), note_search);
        }
    });

    lv.setAdapter(adapter);
    //onClick function
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {

            if (isFABOpen) {
                closeFABMenu();
            }

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String count_title = row2.getString(row2.getColumnIndexOrThrow("count_title"));
            final String count_content = row2.getString(row2.getColumnIndexOrThrow("count_content"));
            final String count_icon = row2.getString(row2.getColumnIndexOrThrow("count_icon"));
            final String count_attachment = row2.getString(row2.getColumnIndexOrThrow("count_attachment"));
            final String count_creation = row2.getString(row2.getColumnIndexOrThrow("count_creation"));

            sharedPref.edit().putString("count_title", count_title).apply();
            sharedPref.edit().putString("count_content", count_content).apply();
            sharedPref.edit().putString("count_seqno", _id).apply();
            sharedPref.edit().putString("count_icon", count_icon).apply();
            sharedPref.edit().putString("count_create", count_creation).apply();
            sharedPref.edit().putString("count_attachment", count_attachment).apply();

            helper_main.switchToActivity(getActivity(), Activity_count.class, false);
        }
    });

    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            if (isFABOpen) {
                closeFABMenu();
            }

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String count_title = row2.getString(row2.getColumnIndexOrThrow("count_title"));
            final String count_content = row2.getString(row2.getColumnIndexOrThrow("count_content"));
            final String count_icon = row2.getString(row2.getColumnIndexOrThrow("count_icon"));
            final String count_attachment = row2.getString(row2.getColumnIndexOrThrow("count_attachment"));
            final String count_creation = row2.getString(row2.getColumnIndexOrThrow("count_creation"));

            final CharSequence[] options = { getString(R.string.number_edit_entry),
                    getString(R.string.bookmark_remove_bookmark), getString(R.string.todo_share),
                    getString(R.string.bookmark_createNote), getString(R.string.bookmark_createEvent) };
            new AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals(getString(R.string.number_edit_entry))) {

                                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                View dialogView = View.inflate(getActivity(), R.layout.dialog_edit_title, null);

                                final EditText edit_title = (EditText) dialogView.findViewById(R.id.pass_title);
                                edit_title.setHint(R.string.bookmark_edit_title);
                                edit_title.setText(count_title);

                                builder.setView(dialogView);
                                builder.setTitle(R.string.bookmark_edit_title);
                                builder.setPositiveButton(R.string.toast_yes,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {

                                                String inputTag = edit_title.getText().toString().trim();
                                                db.update(Integer.parseInt(_id), inputTag, count_content,
                                                        count_icon, count_attachment, count_creation);
                                                setCountList();
                                                Snackbar.make(lv, R.string.bookmark_added,
                                                        Snackbar.LENGTH_SHORT).show();
                                            }
                                        });
                                builder.setNegativeButton(R.string.toast_cancel,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                dialog.cancel();
                                            }
                                        });

                                final AlertDialog dialog2 = builder.create();
                                // Display the custom alert dialog on interface
                                dialog2.show();
                                helper_main.showKeyboard(getActivity(), edit_title);
                            }

                            if (options[item].equals(getString(R.string.todo_share))) {
                                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                                sharingIntent.setType("text/plain");
                                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, count_title);
                                sharingIntent.putExtra(Intent.EXTRA_TEXT, count_content);
                                startActivity(Intent.createChooser(sharingIntent,
                                        (getString(R.string.note_share_2))));
                            }

                            if (options[item].equals(getString(R.string.bookmark_createEvent))) {
                                helper_main.createCalendarEvent(getActivity(), count_title, count_content);
                            }

                            if (options[item].equals(getString(R.string.bookmark_remove_bookmark))) {
                                Snackbar snackbar = Snackbar
                                        .make(lv, R.string.note_remove_confirmation, Snackbar.LENGTH_LONG)
                                        .setAction(R.string.toast_yes, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                db.delete(Integer.parseInt(_id));
                                                setCountList();
                                            }
                                        });
                                snackbar.show();
                            }

                            if (options[item].equals(getString(R.string.bookmark_createNote))) {
                                Notes_helper.newNote(getActivity(), count_title, count_content, "", "", "", "");
                            }

                        }
                    }).show();

            return true;
        }
    });
}

From source file:Main.java

/**
 * Make a textview to a collapsible textview with the indicator on the right of the textview
 * /*w  ww  .  ja v  a  2  s .c  om*/
 * @param tv , {@link TextView} to be converted
 * @param upDrawableResId , drawable resource id to be used as up indicator
 * @param downDrawableResId , drawable resource id to be used as down indicator
 * @param lineTreshold , no of line to be displayed for the collapsed state
 */
public static void makeCollapsible(final TextView tv, int upDrawableResId, int downDrawableResId,
        final int lineTreshold) {

    final Drawable[] drawables = tv.getCompoundDrawables();
    final Drawable up = tv.getContext().getResources().getDrawable(upDrawableResId);
    final Drawable down = tv.getContext().getResources().getDrawable(downDrawableResId);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], down, drawables[3]);
        tv.setEllipsize(TruncateAt.END);
        tv.setMaxLines(lineTreshold);
        tv.setTag(true);
        tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v instanceof TextView) {
                    TextView tv = (TextView) v;
                    boolean snippet = (Boolean) tv.getTag();
                    if (snippet) {
                        // show everything
                        snippet = false;
                        tv.setMaxLines(Integer.MAX_VALUE);
                        tv.setEllipsize(null);
                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], up,
                                drawables[3]);
                    } else {
                        // show snippet
                        snippet = true;
                        tv.setMaxLines(lineTreshold);
                        tv.setEllipsize(TruncateAt.END);
                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], down,
                                drawables[3]);
                    }
                    tv.setTag(snippet);
                }

            }
        });
    } else {
        tv.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

                ViewTreeObserver vto = tv.getViewTreeObserver();
                vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

                    @SuppressWarnings("deprecation")
                    @SuppressLint("NewApi")
                    @Override
                    public void onGlobalLayout() {

                        tv.setEllipsize(TruncateAt.END);
                        int line = tv.getLineCount();
                        tv.setMaxLines(lineTreshold);
                        if (line <= lineTreshold) {
                            tv.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View arg0) {
                                    // empty listener
                                    // Log.d("line count", "count: "+
                                    // tv.getLineCount());
                                }
                            });
                            if (tv.getLayout() != null) {
                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                                    tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                                } else {
                                    tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                                }
                            }
                            return;
                        }

                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], down,
                                drawables[3]);
                        tv.setTag(true);
                        tv.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                if (v instanceof TextView) {
                                    TextView tv = (TextView) v;
                                    boolean snippet = (Boolean) tv.getTag();
                                    if (snippet) {
                                        snippet = false;
                                        // show everything
                                        tv.setMaxLines(Integer.MAX_VALUE);
                                        tv.setEllipsize(null);
                                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1],
                                                up, drawables[3]);
                                    } else {
                                        snippet = true;
                                        // show snippet
                                        tv.setMaxLines(lineTreshold);
                                        tv.setEllipsize(TruncateAt.END);
                                        tv.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1],
                                                down, drawables[3]);
                                    }
                                    tv.setTag(snippet);
                                }

                            }
                        });

                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                            tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        } else {
                            tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    }

                });
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

        });
    }

}

From source file:cm.aptoide.pt.ApkInfo.java

private void loadDescription() {
    Cursor c = getContentResolver().query(ExtrasContentProvider.CONTENT_URI,
            new String[] { ExtrasDbOpenHelper.COLUMN_COMMENTS_COMMENT },
            ExtrasDbOpenHelper.COLUMN_COMMENTS_APKID + "=?", new String[] { viewApk.getApkid() }, null);

    description_text = "";
    if (c.moveToFirst()) {
        description_text = c.getString(0);
    } else {/*from ww w  . j av a2s.co  m*/
        description_text = getString(R.string.no_descript);
    }

    c.close();

    runOnUiThread(new Runnable() {

        @Override
        public void run() {

            final TextView description = (TextView) findViewById(R.id.descript);
            description.setText(description_text);
            if (description.getLineCount() > 10) {
                description.setMaxLines(10);
                findViewById(R.id.show_all_description).setVisibility(View.VISIBLE);
                findViewById(R.id.show_all_description).setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        if (collapsed) {
                            collapsed = false;
                            scrollPosition = findViewById(R.id.app_info_scroller).getScrollY();
                            description.setMaxLines(Integer.MAX_VALUE);
                            ((TextView) findViewById(R.id.show_all_description))
                                    .setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_more_arrow_up,
                                            0);
                            ((TextView) findViewById(R.id.show_all_description))
                                    .setText(getString(R.string.show_less));
                        } else {
                            collapsed = true;
                            ((TextView) findViewById(R.id.show_all_description))
                                    .setCompoundDrawablesWithIntrinsicBounds(0, 0,
                                            R.drawable.ic_more_arrow_down, 0);
                            description.setMaxLines(10);
                            findViewById(R.id.app_info_scroller).scrollTo(0, scrollPosition);
                            ((TextView) findViewById(R.id.show_all_description))
                                    .setText(getString(R.string.show_more));
                        }
                    }
                });
                findViewById(R.id.description_container).setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        if (collapsed) {
                            collapsed = false;
                            scrollPosition = findViewById(R.id.app_info_scroller).getScrollY();
                            description.setMaxLines(Integer.MAX_VALUE);
                            ((TextView) findViewById(R.id.show_all_description))
                                    .setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_more_arrow_up,
                                            0);
                            ((TextView) findViewById(R.id.show_all_description))
                                    .setText(getString(R.string.show_less));
                        } else {
                            collapsed = true;
                            ((TextView) findViewById(R.id.show_all_description))
                                    .setCompoundDrawablesWithIntrinsicBounds(0, 0,
                                            R.drawable.ic_more_arrow_down, 0);
                            description.setMaxLines(10);
                            findViewById(R.id.app_info_scroller).scrollTo(0, scrollPosition);
                            ((TextView) findViewById(R.id.show_all_description))
                                    .setText(getString(R.string.show_more));
                        }
                    }
                });
            }
        }

    });
}