如何在EditText中设置文本

182

如何设置EditText的文本?


10
我想在编辑框中设置文本,这是可能的吗? - user555910
11个回答

319
如果您查看EditText的文档,您将找到一个setText()方法。该方法接受一个String和一个TextView.BufferType。例如:
EditText editText = (EditText)findViewById(R.id.edit_text);
editText.setText("This sets the text.", TextView.BufferType.EDITABLE);

它还继承了 TextViewsetText(CharSequence)setText(int) 方法,因此您可以像设置普通的 TextView 一样进行设置:

editText.setText("Hello world!");
editText.setText(R.string.hello_world);

8
EditText.BufferType.EDITABLE是一个枚举类型,表示可编辑的文本缓冲区类型。 - sll
3
不,EditTextTextView 的子类;TextView.BufferType.EDITABLE 是正确的常量。 - Kevin Coppock
4
新手可能会感到困惑的是setText实际上需要一个CharSequence和一个BufferType。所以要记住字符串是CharSequence的一种。 - Avatar33
7
为什么android.text.Editable存在,或者更好的说,为什么普通开发人员需要绕过它而不是EditText公开一个void setText(CharSequence)方法? - Marcelo Lacerda
3
它确实公开了其超类 TextView 中的 setText(CharSequence) 方法。所以我不太确定为什么这是最受赞和被接受的答案? - Hendy Irawan
显示剩余2条评论

27

如果你正在使用 Kotlin,那么如果你像这样做,它会给你一个错误:

editText.text = "some string"

就像这样使用它

editText.setText("some string")

23

请注意,所有字符串都是CharSequences,因此这个可以工作,但原始的CharSequence不是一个字符串。如果您有一个原始的CharSequence并且需要一个字符串,则需要调用myCharSequence.toString()以获取官方字符串。虽然这对于本应用程序不需要知道,但在其他地方有时是必要的。 - DragonLord

6

这是Kotlin的解决方案

val editText: EditText = findViewById(R.id.main_et_name)
    editText.setText("This is a text.")

6
String text = "Example";
EditText edtText = (EditText) findViewById(R.id.edtText);
edtText.setText(text);

请注意,EditText只接受字符串类型的值,如果需要,请将其转换为字符串。

如果是整型、双精度型或长整型数值,则执行以下操作:

String.value(value);

4
您可以设置android:text="您的文本";
<EditText
    android:id="@+id/editTextName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/intro_name"/>

4
如果你想在xml文件中在设计时设置文本,只需添加android:text="username"属性即可。
<EditText
    android:id="@+id/edtUsername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="username"/>

如果您想在Java中以编程方式设置文本

EditText edtUsername = findViewById(R.id.edtUsername);
edtUsername.setText("username");

kotlin 中与 Java 相同,使用 getter/setter。

edtUsername.setText("username")

但是如果你想从原则上使用.text,那么

edtUsername.text = Editable.Factory.getInstance().newEditable("username")

由于EditText.text 首先需要一个可编辑对象(editable),而不是字符串(String)。

3
使用+,字符串拼接操作符:
 ed = (EditText) findViewById (R.id.box);
    int x = 10;
    ed.setText(""+x);

或者使用
String.valueOf(int):
ed.setText(String.valueOf(x));

或者使用。
Integer.toString(int):
ed.setText(Integer.toString(x));


1
您需要:
  1. 在xml文件中声明EditText
  2. 在活动中找到EditText
  3. 设置EditText的文本

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