【问题标题】:negative number input(EditText) getting unsigned负数输入(EditText)变得无符号
【发布时间】:2011-10-04 19:40:54
【问题描述】:

我正在做一个电缆长度计算器,但我遇到了负数问题。

EditTexts 是这样的

<EditText android:layout_height="wrap_content" android:layout_weight="1" android:inputType="numberDecimal|numberSigned" android:layout_width="40px" android:id="@+id/rxmax">
        </EditText>

然后我像这样使用它们:

final EditText rxmax = (EditText) findViewById(R.id.rxmax);
double RXmax = new Double(rxmax.getText().toString());

经过简单的计算:

double OPBmax = TXmax - RXmax;

某处输入的负数变为正数。我在猜测 toString 对话,但我没有找到任何关于如何防止这种情况的信息。

【问题讨论】:

    标签: android numbers android-edittext


    【解决方案1】:

    使用 android:digits="0123456789"

    前:

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:digits="0123456789"
            android:gravity="center"
            android:inputType="numberSigned"
            android:textColor="@color/black"
            android:textSize="@dimen/font_size_small" />
    

    【讨论】:

      【解决方案2】:

      我试过了,效果很好……

      活动:

      double RXmax;
      EditText rxmax;
      TextView tv;
      
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
      
          rxmax = (EditText) findViewById(R.id.rxmax);
          tv = (TextView) findViewById(R.id.text);
      }
      
      public void click(View v) {
          RXmax =  new Double(rxmax.getText().toString());
          tv.setText(Double.toString(RXmax));
      }
      

      main.xml:

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:layout_width="fill_parent"
          android:layout_height="fill_parent">
          <EditText android:layout_height="wrap_content"
              android:layout_weight="1" android:inputType="numberDecimal|numberSigned"
              android:layout_width="40px" android:id="@+id/rxmax">
          </EditText>
      
          <TextView android:id="@+id/text" android:layout_width="fill_parent"
              android:layout_height="wrap_content" android:text="@string/hello" />
      
          <Button android:layout_height="wrap_content" android:id="@+id/button1"
              android:layout_weight="1" android:text="Button" android:layout_width="wrap_content"
              android:onClick="click"></Button>
      
      </LinearLayout>
      

      如果我输入 -2,点击 TextView 后会显示 -2.0

      如果您使用的是 Eclipse,请尝试 Project --> Clean...,然后选择您的项目。也许这会有所帮助。

      【讨论】:

      • 这也是一个好主意,虽然它接缝了我最初的想法也有效,只是错误地输入了错误的测试编号。我非常感谢您的帮助!
      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 2013-07-22
      • 2014-08-30
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多