【问题标题】:Control the edittext contents in android控制android中的edittext内容
【发布时间】:2015-10-01 12:32:23
【问题描述】:

我有一些编辑文本来获取一些整数。 现在我想控制它们的内容。例如如果写的数字在 1 到 22 之间,请执行一些操作。

如何从 editText 获取文本并将它们转换为 int 进行比较?

【问题讨论】:

  • 什么时候应该发生?点击按钮后?
  • 是的!没错,我忘记写了

标签: android android-edittext logic


【解决方案1】:

如果您的按钮是 btn 并且 editText 是 edt 则执行以下操作

btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
        int a;
        a=Integer.parseInt(edt.getText().toString());

        if(a>1 && a<22)
        {
           //do something here
        }
         }
       });

【讨论】:

  • 是的。 a 是整数值@MinaDahesh
【解决方案2】:

在按钮的 onClickListener 中试试这个:

try {
   int number = Integer.parseInt(editText.getText().toString());
   if(number >= 1 && number < 22) {
      // do smth
   }
} catch (NumberFormatException e){
   Log.d(LOG_TAG, "Could not convert text into integer");
}

【讨论】:

  • 谢谢,但为什么要写数字!=null,数字是整数而不是布尔值?
  • 检查空指针总是好的。 :) 但在这种情况下你是对的。除了数字之外的任何字符串都是无效的,并且会抛出 NumberFormatException。我会编辑我的答案。
【解决方案3】:

使用TextWatcher

public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(check){
                 //do stuff
             }
}

【讨论】:

    【解决方案4】:
    editText.addTextChangedListener(myTextWatcher);
    

    在你的 myTextWatcher 中

    TextWatcher myTextWatcher= new TextWatcher() {
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            }
    
            public void onTextChanged(CharSequence s, int start, int before, int count) {
              if(Integer.parseInt(s)>1 && Integer.parseInt(s)<=22)
              {
                 // perform you action
              }
            }
    
            public void afterTextChanged(Editable s) {
    
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 2016-05-17
      相关资源
      最近更新 更多