You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio Java填空游戏:TextView换行内容拆分异常问题

问题原因与解决方案

核心问题分析

你遇到的getLineCount()始终返回1、无法正确转移换行内容的问题,核心是两个逻辑错误导致的:

  1. 递归顺序颠倒:你的checkNumberOfLines方法先截断文本再检查行数,永远无法获取原始长文本的实际行数,每次检查的都是已缩短的文本,自然返回1。
  2. 终止条件错误:用if (lineCount > 0)触发递归,会导致只要文本不为空就持续拆分,直到secondSentence被拆空,完全偏离“转移换行内容”的需求。

修复后的代码实现

先重构checkNumberOfLines方法,改为先检查行数,再决定是否拆分:

private void checkNumberOfLines() {
    secondSentence.post(new Runnable() {
        @Override
        public void run() {
            int lineCount = secondSentence.getLineCount();
            // 仅当第二行文本行数超过1时,才拆分转移内容
            if (lineCount > 1) {
                String currentText = secondSentence.getText().toString().trim();
                int lastSpaceIndex = currentText.lastIndexOf(" ");
                // 确保还有可拆分的单词,避免单个单词时报错
                if (lastSpaceIndex != -1) {
                    String firstPart = currentText.substring(0, lastSpaceIndex);
                    String lastWord = currentText.substring(lastSpaceIndex + 1);
                    // 更新第二行文本
                    secondSentence.setText(firstPart);
                    // 将拆分出的单词追加到第三行,保持原句顺序
                    String thirdCurrent = thirdSentence.getText().toString().trim();
                    thirdSentence.setText(lastWord + (thirdCurrent.isEmpty() ? "" : " ") + thirdCurrent);
                    // 递归检查,直到第二行行数≤1
                    checkNumberOfLines();
                } else {
                    newLineBoolean = false;
                }
            } else {
                newLineBoolean = false;
            }
        }
    });
}

同时调整onCreate的初始化逻辑,确保文本设置正确后再触发检查:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout_id); // 替换为你的布局ID

    answerText = findViewById(R.id.answerPlace);
    firstSentence = findViewById(R.id.firstSentence);
    secondSentence = findViewById(R.id.secondSentence);
    thirdSentence = findViewById(R.id.thirdSentence);

    sentenceDivision = sentence.split(keyword);
    firstSentence.setText(sentenceDivision[0]);
    // 移除文本前后空格,避免无效换行
    secondSentence.setText(sentenceDivision[1].trim());

    // 生成关键词占位符
    displayForKeyword = "";
    for (int i = 0; i < keyword.length(); i++) {
        displayForKeyword += "   ";
    }
    answerText.setText(displayForKeyword);

    // 初始化第三行文本为空
    thirdSentence.setText("");
    thirdLine = "";

    // 启动行数检查逻辑
    checkNumberOfLines();
}

额外布局注意事项

确保布局满足以下条件,否则文本无法正常换行:

  • secondSentence的android:layout_width设置为match_parent或固定宽度(不能是wrap_content)
  • 未设置android:singleLine="true"或android:maxLines="1"属性

内容的提问来源于stack exchange,提问作者Nacho Novoa Mayo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:35:24