Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.graphics.Paint;

import android.util.DisplayMetrics;
import android.view.View;

import android.widget.TextView;

public class Main {
    public static int applyNewLineCharacter(TextView textView) {
        Paint paint = textView.getPaint();
        String text = (String) textView.getText();
        int frameWidth = getPixelFromDp(textView, 120f);
        int startIndex = 0;
        int endIndex = paint.breakText(text, true, frameWidth, null);
        String save = text.substring(startIndex, endIndex);
        // Count line of TextView
        int lines = 1;

        while (true) {
            // Set new start index
            startIndex = endIndex;
            // Get substring the remaining of text
            text = text.substring(startIndex);

            if (text.length() == 0) {
                break;
            } else {
                lines++;
            }

            // Calculate end of index that fits
            endIndex = paint.breakText(text, true, frameWidth, null);
            // Append substring that fits into the frame
            save += "\n" + text.substring(0, endIndex);
        }
        // Set text to TextView
        textView.setText(save);

        return lines;
    }

    public static int getPixelFromDp(View view, float dp) {
        DisplayMetrics metrics = view.getContext().getResources().getDisplayMetrics();

        float fpixels = metrics.density * dp;
        int pixels = (int) (metrics.density * dp + 0.5f);

        return pixels;
    }
}