[英]How To Set Text In An EditText
如何设置 EditText 的文本?
如果您查看EditText
的文档,您会发现setText()
方法。 它接受一个String
和一个TextView.BufferType
。 例如:
EditText editText = (EditText)findViewById(R.id.edit_text);
editText.setText("This sets the text.", TextView.BufferType.EDITABLE);
它还继承了TextView
的setText(CharSequence)
和setText(int)
方法,因此您可以像常规TextView
一样设置它:
editText.setText("Hello world!");
editText.setText(R.string.hello_world);
String string="this is a text";
editText.setText(string)
我发现 String 是 CharSequence 的一个有用的间接子类
http://developer.android.com/reference/android/widget/TextView.html找到 setText(CharSequence text)
http://developer.android.com/reference/java/lang/CharSequence.html
String text = "Example";
EditText edtText = (EditText) findViewById(R.id.edtText);
edtText.setText(text);
检查出来EditText
只接受字符串值,如有必要将其转换为字符串。
如果是 int、double、long 值,请执行以下操作:
String.value(value);
这是 Kotlin 中的解决方案
val editText: EditText = findViewById(R.id.main_et_name)
editText.setText("This is a text.")
如果您使用的是 kotlin,那么如果您这样做,它会给您错误
editText.text = "some string"
就像使用它一样
editText.setText("some string")
使用 +,字符串连接运算符:
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));
你可以设置android:text="your text"
;
<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/intro_name"/>
你需要:
EditText in the xml file
声明EditText in the xml file
EditText
EditText
设置文本editTextObject.setText(CharSequence)
http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence )
Android Java 中的解决方案:
启动你的 EditText,ID 是你的 xml id。
EditText myText = (EditText)findViewById(R.id.my_text_id);
在您的 OnCreate 方法中,只需按定义的名称设置文本。
String text = "here put the text that you want"
使用您的 editText 中的 setText 方法。
myText.setText(text); //variable from point 2
如果您想在设计时在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
与使用 getter/setter 的 java 一样
edtUsername.setText("username")
但是如果你想从原则中使用.text
那么
edtUsername.text = Editable.Factory.getInstance().newEditable("username")
因为EditText.text
需要一个editable
而不是String
如果在“回收者”视图中有文本,该如何解决?单击它,我想在“回收者”视图中打开带有文本的编辑文本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.