【问题标题】:can i know pls the INPUT variable why it's giving me error always, thank you so much我能知道输入变量为什么它总是给我错误,非常感谢
【发布时间】:2020-12-01 17:46:27
【问题描述】:

我能知道为什么input 变量为什么总是给我错误,非常感谢。

下面是我的代码:


public class MainActivity extends AppCompatActivity {

      public TextView textView;
       public EditText editText;
      public Button btn;
      public int input;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=findViewById(R.id.textView);
        editText = findViewById(R.id.editText);
        btn = findViewById(R.id.btn);

      ` input= Integer.parseInt(editText.getText().toString());`


        btn.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {

                textView.setText(input );

            }
        });
    }
}

【问题讨论】:

    标签: android user-input gettext


    【解决方案1】:

    由于无法将 String 转换为 integer,因此发生错误。这可能是因为您的 editText 为空,或者您的字符不是整数(例如字母)。因此,您应该使用trycatch 来捕获错误。

    【讨论】:

      【解决方案2】:

      目前,您正在尝试在创建视图后立即在 onCreate() 中解析来自 editText 的输入字符串。这将尝试解析与 editText 关联的默认文本。我认为您想要的是在单击按钮时解析输入。在这种情况下,将输入解析代码移动到 onClick() 中。此外,如果您不能保证在 EditText 中输入的文本始终为整数,则最好在调用 parseInt() 时捕获 NumberFormatException。

          @Override
          public void onClick(View v) {
              android.util.Log.i("MyActivity", "onClick: edit text = " + editText.getText());
              input= Integer.parseInt(editText.getText().toString());
              textView.setText(input );
          }
      

      【讨论】:

      • 非常感谢您的快速响应,我做到了并在点击视图之后移动了输入行,但它也给了我错误,抱歉打扰了,但我早上和现在做了它不工作不知道是什么错误。
      • 你能粘贴你得到的错误信息吗?尝试解析 EditText 中的文本时,我认为它是 NumberFormatException。确保在 EditText 中输入的文本始终是整数。我已经编辑了答案以包含一个 Log 语句,该语句可以在单击按钮时在 EditText 中打印文本。另一种方法是使用 Android Studio 中的调试器选项来检查值。
      猜你喜欢
      • 2021-05-11
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多