setText()和append()之间的区别

时间:2013-10-14 05:30:39

标签: android append textview settext

我很好奇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 个答案:

答案 0 :(得分:11)

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

//这里lineNumbers有它是测试

lineNumbers将“正在测试”。之后,如果再次使用setText,文本将完全更改

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

//这里你将丢失第一个文本,lineNumbers文本将是“它是   第二次测试,“

之后,如果你使用追加,让我们看看会发生什么......

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

//在这里不会丢失 lineNumbers文本..就像这样 “这是第二次测试,是第三次测试”

答案 1 :(得分:6)

setText():通过填写要设置的文本来销毁缓冲区内容。 append():将文本添加到缓冲区,然后打印结果。

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

答案 2 :(得分:4)

setText将使用新文本替换现有文字。

  

来自Android doc:
  设置此TextView要显示的文本(请参阅setText(CharSequence))并设置是否   存储在一个可样式/可跨越的缓冲区中,是否可编辑。

append将保留旧文本并添加新文本,就像连接一样。

  

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

答案 3 :(得分:2)

我认为通过append方法将BufferType更改为EDITABLE会导致意外的填充。 如果要使用append方法而不是setText方法并删除该填充,

您可以尝试使用

删除它
textView.setincludeFontPadding(false)

或将此行添加到xml文件中的textview

android:includeFontPadding="false"

希望这有帮助。

答案 4 :(得分:1)

基本区别在于setText()会替换现有文本中的所有文字,append()会将新值添加到现有文本中。希望我能帮忙。

相关问题