Как получить многострочный текст из Edittext? - PullRequest
2 голосов
/ 23 мая 2019

Я хочу получить текст (многострочный) из Edittext, такой же, как данный снимок экрана.

Я хочу получить вывод ниже, когда getText () из Edittext.

Вывод:

Lorem Ipsum - просто глупый

текст печатной и

печатной индустрии.Lorem

Ipsum был стандартным

стандартным фиктивным текстом.

enter image description here

Я пробовал решение ниже, но,это не работает

etMessage.getText().toString().replaceAll("\\n", "<br />")

Ответы [ 3 ]

2 голосов
/ 25 июня 2019

После долгих поисков и ожидания ответа на этот вопрос.Я решил эту проблему.

Решение: Я измерил каждую строку и слова, чтобы сохранить их как многострочный текст, для этого можно использовать функцию ниже.

DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;

String result = fitString(ipText, ipText.getText().toString());

private String fitString(EditText editText, String message) {

        Log.i(TAG, "fitString: Default String : " + message);

        StringBuilder finalMessage = new StringBuilder();

        if (isTooLarge(editText, message)) {
            Log.i(TAG, "fitString: isTooLarge 1 : " + true);
            List<String> lineList = Arrays.asList(message.split("\n"));
            Log.i(TAG, "fitString: stringList" + lineList);

            if (lineList != null && lineList.size() > 0) {

                for (int i = 0; i < lineList.size(); i++) {

                    if (lineList.get(i) != null && !lineList.get(i).isEmpty()) {

                        if (isTooLarge(editText, lineList.get(i))) {
                            Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + true);

                            List<String> wordList = Arrays.asList(lineList.get(i).split(" "));
                            Log.i(TAG, "fitString: wordList" + wordList);

                            if (wordList != null && wordList.size() > 0) {
                                Log.i(TAG, "fitString: wordList : " + wordList.size());

                                StringBuilder temp = new StringBuilder();
                                String lastWord = "";

                                for (int j = 0; j < wordList.size(); j++) {

                                    if (wordList.get(j) != null && !wordList.get(j).isEmpty()) {

                                        if (isTooLarge(editText, wordList.get(j))) {
                                            Log.i(TAG, "fitString: isTooLarge 3 : " + wordList.get(j) + " == " + true);
                                            String newString = fitCharacter(editText, wordList.get(j));
                                            Log.i(TAG, "fitString: fitCharacter == " + newString);

                                            if (j == (wordList.size() - 1) && i == (lineList.size() - 1)) {
                                                finalMessage.append(newString);
                                            } else {
                                                finalMessage.append(newString + "\n");
                                            }

                                        } else {

                                            if (j == 0) {
                                                lastWord = wordList.get(j);
                                            } else {
                                                lastWord = " " + wordList.get(j);
                                            }


                                            temp.append(lastWord);
                                            Log.i(TAG, "fitString: temp : " + temp);
                                            Log.i(TAG, "fitString: lastWord : " + lastWord);

                                            if (isTooLarge(editText, temp.toString())) {
                                                temp.setLength(0); // clear String Builder,  new StringBuilder()
                                                temp.append(lastWord);
                                                if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
                                                    Log.i(TAG, "fitString: ###### 1");
                                                    finalMessage.append("\n" + lastWord.trim() + "\n");
                                                } else {
                                                    Log.i(TAG, "fitString: ###### 2");
                                                    finalMessage.append("\n" + lastWord.trim());
                                                }

                                            } else {

                                                if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
                                                    Log.i(TAG, "fitString: ###### 3");
                                                    finalMessage.append(lastWord + "\n");
                                                } else {
                                                    Log.i(TAG, "fitString: ###### 4");
                                                    finalMessage.append(lastWord);
                                                }

                                            }

                                            Log.i(TAG, "fitString: finalMessage : " + finalMessage);
                                        }

                                    } else {
                                        Log.e(TAG, "fitString: Word is Null or Empty.");
                                        finalMessage.append(" ");
                                    }

                                }

                            } else {
                                Log.e(TAG, "fitString: wordList is Null or Empty.");
                            }


                        } else {
                            Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + false);
                            if (i == (lineList.size() - 1)) {
                                finalMessage.append(lineList.get(i));
                            } else {
                                finalMessage.append(lineList.get(i) + "\n");
                            }
                        }
                    } else {
                        Log.e(TAG, "fitString: Line is Null or Empty.");
                        finalMessage.append(lineList.get(i) + "\n");
                    }
                }
            } else {
                Log.e(TAG, "fitString: stringList is Null or Empty.");
                finalMessage.append("");
            }

            return finalMessage.toString();

        } else {
            Log.i(TAG, "fitString: isTooLarge : " + false);
            return message;
        }
    }

    public String fitCharacter(EditText editText, String message) {

        Log.i(TAG, "fitCharacter2: Default Word : " + message);

        StringBuilder finalWord = new StringBuilder();
        int startIndex = 0;
        int endIndex = 1;


        for (; ; ) {

            String tempSplitWord = message.substring(startIndex, endIndex);
            Log.i(TAG, "fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " tempSplitWord : " + tempSplitWord);
            if (!isTooLarge(editText, tempSplitWord)) { // isTooLarge
                if (endIndex < message.length()) {
                    endIndex = endIndex + 1;
                    Log.i(TAG, "IF fitCharacter2: endIndex < message.length() " + endIndex + " < " + message.length());
                } else {
                    String result = finalWord.append(tempSplitWord).toString();
                    Log.i(TAG, "IF RETURN RESULT : " + result);
                    return result;
                }
            } else {
                endIndex = endIndex - 1;
                String splitWord = message.substring(startIndex, endIndex);
                Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " splitWord : " + splitWord);

                boolean isTooLarge = isTooLarge(editText, splitWord);
                if (!isTooLarge) {
                    finalWord.append(splitWord + "\n");
                }
                startIndex = endIndex;
                endIndex = endIndex + 1;
                Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex);
            }
        }
    }

    private boolean isTooLarge(EditText editText, String newText) {
        if (editText != null && editText.getPaint() != null) {
            float textWidth = editText.getPaint().measureText(newText);

            return (textWidth >= (editText.getMeasuredWidth() - (12 * density))); // editText.getMeasuredWidth();
        } else {
            return false;
        }
    }
1 голос
/ 23 мая 2019

По умолчанию все виджеты EditText в Android являются многострочными. И вы можете настроить количество линий и типы символов. Установив тип ввода для многострочного, сделайте свое дело.

<EditText 
   ...
   android:inputType="textMultiLine" <!-- Multiline input -->
   ...
   android:lines="8" <!-- Total Lines prior display -->
   android:minLines="6" <!-- Minimum lines -->
   android:gravity="top|left" <!-- Cursor Position -->
   android:maxLines="10" <!-- Maximum Lines -->
   android:layout_height="wrap_content" <!-- Height determined by content -->
   android:layout_width="match_parent" <!-- Fill entire width -->
   android:scrollbars="vertical" <!-- Vertical Scroll Bar -->
/>
0 голосов
/ 23 мая 2019

вы пробовали это

message = etMessage.getText().toString().replaceAll("\\n", "<br />")

пожалуйста, смотрите это также Как сохранить разрывы строк из EditText?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...