简体   繁体   English

如何在运行时设置EditText的文本值?

[英]How to set the text value of EditText at run time?

I have an edit text field and I want to set the value of this field(to an integer) dynamically at run time. 我有一个编辑文本字段,我想在运行时动态设置此字段的值(为整数)。 As the EditText field accepts strings by default, how do I proceed with this? 由于默认情况下EditText字段接受字符串,我该如何进行呢?

Take a look at String.valueOf method : 看一下String.valueOf方法:

int someInt = 5;
myEditText.setText(String.valueOf(someInt))

You can change the input type of the editText at the XML end to force the user to input Integer Values only. 您可以在XML端更改editText的输入类型,以强制用户仅输入Integer Values。

As for setting the values programmatically at runtime, do this: 至于在运行时以编程方式设置值,请执行以下操作:

EditText editText = (EditText)findViewById(R.id.editText1);
int input = 4;
editText.setText(string.ValueOf(input));

set the property of edittext to accept integers only, if this is what you want by adding following property in your xml file that contains the edittext. 通过在包含edittext的xml文件中添加以下属性,将edittext的属性设置为仅接受整数。

android:inputType="number"

For doing calculations, if the value entered is number you can use following function:- 进行计算时,如果输入的值是数字,则可以使用以下功能:-

EditText editText = (EditText)findViewById(R.id.editText);
int editTextValue = Integer.parseInt(editText.getText().toString());

now you can perform calculations on the same. 现在您可以在同一位置执行计算。

For setting an int to editText, you can use following:- 要将int设置为editText,可以使用以下命令:

editText.setText(""+editTextValue);//here editTextValue is the number which you want to set in editText field.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM