【问题标题】:Prevent negative numbers in Textview android - Code防止Textview android中的负数 - 代码
【发布时间】:2014-12-15 11:51:33
【问题描述】:

是否可以通过在java中编写代码来停止在android的TextView中获取负数。

我试过了

int up = 0;
TextView textview;

        if (allowNagativeNumbers == false) {
            if ( up < 0 ) 
            {
                up = 0;
                textview.setText(0);
            }
        }

但它仍然允许负数。我不确定这段代码是否正确,但这段代码我的意思是每次 textview 中 up / text 的值小于 0 时,例如-1 然后将值更改为 0 并使 textview 文本为 0。

【问题讨论】:

  • 使用 NumberSpinner 代替
  • 我必须使用 textview
  • 基本上,在我的应用程序中有一个按钮,如果按下该按钮,textview 将停止执行负数,但如果未按下该按钮,那么它将与正数一起执行负数。
  • 如果没有一个很好的代码示例来说明您的问题,就无法为您提供帮助。
  • 感谢您的帮助,我找到了解决方案。

标签: java android textview negative-number


【解决方案1】:

TextView 中显示您的号码之前,请在您的号码上使用Math.abs() 函数。此函数将为您提供绝对值。

【讨论】:

    【解决方案2】:

    我猜你希望这实时发生?您是否在为 textview 使用侦听器?如果是这样,请确保它在侦听器中,并仔细检查并确保 allowNegativeNumbers 实际上是错误的。

    【讨论】:

      【解决方案3】:

      实现您自己的 TextView 类(您也可以在 XML 文件中使用它)。

      public class MyTextView extends TextView {
      
          @Override
          public void setText (CharSequence text, BufferType type)
          {
              if(Integer.valueOf(text) > 0)
              {
                  super.setText (text, type);
              }
              else
              {
                  super.setText ("0", type);
              }
      
      }
      

      【讨论】:

        【解决方案4】:

        试试这些语句

        int up = 5;
        up = up >0 ? up: 0;
        
        and set the text in textView.
        

        另一种方式

        从 textView 中获取文本并将其转换为字符串。

        int up = Integet.parseInt(textView.getText());
        up = up >0 ? up: 0;
        and set the text in textView.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-23
          • 1970-01-01
          相关资源
          最近更新 更多