提问者:小点点

如何将TextView(id)返回为double?


TextView布局

mTextValue = (TextView) findViewById(R.id.amount2);

能在另一个私人空间里得到这样的东西:

double amount= mTextValue;

XML

<TextView
    android:id="@+id/amount2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:hint="amount"
    android:inputType="number"
    android:text="15"
    android:textColor="@android:color/black"
    android:textSize="24sp"
    app:layout_constraintStart_toEndOf="@+id/Total"
    app:layout_constraintTop_toTopOf="@+id/Total" />

我想获得TextView并将其用作double并返回为be(返回金额2*100);


共2个答案

匿名用户

您将TextView的值作为String获得。您需要将其解析为double。

Double.valueOf(mTextValue.getText());

您需要确保TextView中的文本是double,否则此方法将引发异常。

匿名用户

使用edittext从用户获取输入,而不是使用textView:

<EditText
    android:id="@+id/amount2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:hint="amount"
    android:inputType="number"
    android:text="15"
    android:textColor="@android:color/black"
    app:layout_constraintStart_toEndOf="@+id/Total"
    app:layout_constraintTop_toTopOf="@+id/Total" />

然后使用以下命令获取用户输入值:

    final EditText amountEt = findViewById(R.id.amount2); // find the edit text
    final String userInput = amountEt.getText().toString(); // get the edittext value entered
final double amount;

if(!userInput.isEmpty()) {
try {
   amount = Double.parseDouble(userInput);
} catch (Exception e) {
   e.printStackTrace();
}
} else {
 // show empty input message
}

   // do the other stuffs