简体   繁体   English

获取 EditText 的 int 值

[英]Get int Value Of EditText

I cant Get int Value Of EditText In Androis Studio I Use Int FirstValue = Integer.parseInt(FirstInput.getText().toString());我无法在 Androis Studio 中获取 EditText 的 int 值我使用Int FirstValue = Integer.parseInt(FirstInput.getText().toString()); But when i Use it My App will Has Stopped In Evulator !但是当我使用它时,我的应用程序将在 Evulator 中停止! this Problem is For All Of My Android Studio Applications这个问题适用于我所有的 Android Studio 应用程序

First, make sure that your EditText has an id in your layout file.首先,确保您的 EditText 在您的布局文件中有一个id

<EditText 
android:id="@+id/FirstInput" 
android:width="220px" />

Next, in your activity, make sure you have the following code, it doesn't have to be in your onCreate() method as the EditText will have an empty value.接下来,在您的活动中,确保您有以下代码,它不必在您的onCreate()方法中,因为 EditText 将有一个空值。 But the same basic principals apply;但同样的基本原则适用;

EditText FirstInput;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

    FirstInput   = (EditText)findViewById(R.id.FirstInput);
    try{
    int firstValue = Integer.parseInt(FirstInput.getText().toString());
    }catch(Exception e){
     // Do something to handle the error;
    }
}

It's它是

if(!FirstInput.getText().toString().equals(""){
int firstValue = Integer.parseInt(FirstInput.getText().toString());
} else {
 //Display a toast for handling null value in EditText or something.
}

It is still crashing means, You are not using the valid id for the EditText or you are trying to convert the integer which is not a number(as the string).它仍然是崩溃的意思,您没有使用 EditText 的有效 ID,或者您正在尝试转换不是数字的整数(作为字符串)。

Try with having some try catch blocks for the above code block and see.尝试为上述代码块添加一些 try catch 块并查看。 Still if you are not able to see the Number format exception, It is definitely with the id of the EditText or the edittext may not present in the layout you are using( eg: the edittext exists in layout-large but not layout directory layout file)仍然如果你看不到数字格式异常,它肯定是 EditText 的 id 或者你正在使用的布局中可能不存在 edittext(例如:edittext 存在于布局大但不是布局目录布局文件中)

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

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