Android:将Int转换为String而反之亦然(在侦听器中使用try和catch)

[英]Android: converting Int to String and viceversa (Using try and catch in listener)


I want to get the integer from the editText and by pressing the button, show the input in textView. The problem is the result is always zero. Thanks in advance for your helps.

我想从editText中获取整数,然后按下按钮,在textView中显示输入。问题是结果总是为零。在此先感谢您的帮助。

    EditText editText = (EditText) findViewById(R.id.editText);
    TextView textView = (TextView) findViewById(R.id.textView);
    Button button = (Button) findViewById(R.id.button);
    try{
    String string = editText.getText().toString();
    int num = Integer.parseInt(string);}
    catch(NumberFormatException numb){
        Toast.makeText(this, "Problem", Toast.LENGTH_SHORT).show();
    }
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String number = String.valueOf(num);
            textView.setText(number);
        }
    });

2 个解决方案

#1


1  

You need to read EditText value in onClick method to retrieve the updated value

您需要在onClick方法中读取EditText值以检索更新的值

EditText editText = (EditText) findViewById(R.id.editText);
TextView textView = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        try{
            String string = editText.getText().toString();
            int num = Integer.parseInt(string); // retrieve the updated value
            String number = String.valueOf(num);
            textView.setText(number);
        }
        catch(NumberFormatException numb){
            Toast.makeText(this, "Problem", Toast.LENGTH_SHORT).show();
        }
    }
});

#2


0  

You have to do all the value look-ups and computation in the listener itself. From what I see here, the string is empty when you initially set "num".

您必须在侦听器本身中执行所有值查找和计算。从我在这里看到的,当你最初设置“num”时,字符串是空的。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2017/03/22/4a21f59e9b001cbc2177b539ab27dca4.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号