我很好奇setText()和append()正在创建的差异。我正在编写一个带有行号的非常基本的编辑器。我有一个文本视图来保存左侧的行号,右侧有一个 EditText 来保存数据。下面是 XML:
<LinearLayout 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"
android:gravity="top">
<TextView
android:id="@+id/line_numbers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="0dip"
android:gravity="top"
android:textSize="14sp"
android:textColor="#000000"
android:typeface="monospace"
android:paddingLeft="0dp"/>
<EditText
android:id="@+id/editor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text|textMultiLine|textNoSuggestions"
android:imeOptions="actionNone"
android:gravity="top"
android:textSize="14sp"
android:textColor="#000000"
android:typeface="monospace"/>
</LinearLayout>
忽略我正在做的其他一些事情,我遇到的最奇怪的事情是当我使用 append() 时出现的额外间距(假设事情已经初始化等等)。
下面与 XML 结合使用,在文本视图和编辑文本之间设置一个齐平边框。
theEditor = (EditText) findViewById(R.id.editor);
lineNumbers = (TextView) findViewById(R.id.line_numbers);
theLineCount = theEditor.getLineCount();
lineNumbers.setText(String.valueOf(theLineCount)+"n");
但是,将最后一行更改为此行,突然间,TextView 中的每一行在 EditText 之前的右侧都有填充。
lineNumbers.append(String.valueOf(theLineCount)+"n");
这不是世界末日。 但我很好奇是什么导致了这种行为。由于我是该语言的新手,我唯一能想到的是,当附加物在那里抛出可编辑性时,它会添加填充。如果我能得到答案,我可以用更简单的附加词替换所有这些讨厌的行:
lineNumbers.setText(lineNumbers.getText().toString()+String.valueOf(newLineCount)+"n");
lineNumbers.setText("It is test,");
//这里行数字有它是测试
lineNumbers将具有"这是测试"。之后,如果您再次使用 setText,文本将完全更改
lineNumbers.setText("It is second test,");
在这里你会丢失第一个文本,行数字文本将是"它是 第二次测试,"
之后,如果你使用append,让我们看看会发生什么。
lineNumbers.append("It is third test,");
在这里你不会丢失行数字文本。会是这样的"这是第二次测试,这是第三次测试"
setText():
通过填充要设置的文本来销毁缓冲区内容。 append():
将文本添加到缓冲区,然后打印结果。
示例:example.setText("Hello");
将在输出屏幕上打印 Hello。如果你然后执行example.append("World");
你会得到HelloWorld作为输出。
setText
将用新文本替换现有文本。
来自安卓文档:
设置此文本视图要显示的文本(请参见 setText(CharSequence)),并设置是否显示 存储在可设置样式/可跨度的缓冲区中,以及它是否可编辑。
追加将保留旧文本并添加新文本,更像连接。
来自安卓文档
方便的方法:将指定的文本追加到 TextView 的显示缓冲区,将其升级为 BufferType.EDITABLE(如果它尚未可编辑)。
我认为通过追加方法将 BufferType 更改为可编辑会导致意外的填充。如果要使用追加方法而不是 setText 方法并删除该填充,
您可以尝试使用
textView.setincludeFontPadding(false)
或将此行添加到 XML 文件的文本视图中
android:includeFontPadding="false"
希望这有帮助。
基本区别在于setText()
替换现有文本中的所有文本,append()
将新值添加到现有文本中。希望我有帮助。