setText()和append()的区别

11

我很好奇setText()和append()之间的区别。我正在编写一个非常基本的带有行号的编辑器。我有一个TextView在左侧用于保存行号,右侧是一个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结合使用,在TextView和EditText之间设置了一个清晰边框。

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");
5个回答

15
lineNumbers.setText("It is test,");

//这里lineNumbers有它是测试

lineNumbers将有“它是测试,”。之后,如果再次使用setText,则文本将完全更改

lineNumbers.setText("It is second test,");

//在这里,您将失去第一个文本,并且lineNumbers文本将成为"这是第二个测试,"

之后,如果您使用append,让我们看看会发生什么..

lineNumbers.append("It is third test,");

// 在这里你不会失去行号文本.. 会像这样 "这是第二个测试,这是第三个测试"


6

setText(): 将要设置的文本填充到缓冲区中,覆盖原有内容。

append(): 将文本添加到缓冲区中,并将结果输出。

例如:example.setText("Hello"); 将在输出屏幕上打印出 Hello。如果您随后执行 example.append("World");,则会得到 HelloWorld 作为输出结果。


不以任何方式解决问题的内容(也许是标题,但不是确切问题的描述)。 - Antonio

4

setText会用新文本替换现有文本。

来自Android文档:
设置此TextView要显示的文本(请参阅setText(CharSequence)),同时设置它是否存储在可设置/可扩展缓冲区中以及它是否可编辑。

append会保留旧文本并添加新文本,更像是连接操作。

来自Android文档:
方便方法:将指定的文本附加到TextView的显示缓冲区中,如果它尚未可编辑,则将其升级为BufferType.EDITABLE。


2
我认为通过使用append方法将BufferType更改为EDITABLE导致了意外的填充。 如果你想使用append方法而不是setText方法,并且去除那个填充,你可以尝试使用以下方法来去除它:
textView.setincludeFontPadding(false)

或者在您的XML文件中将此行添加到TextView中。
android:includeFontPadding="false"

希望这能帮到你。

1
基本区别在于setText()会替换现有文本中的所有内容,而append()会将新值添加到现有文本中。希望能帮到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接