如何将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并返回为(return amount2*100(;

您可以将TextView的值作为String。您需要将其解析为双精度。

Double.valueOf(mTextValue.getText());

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

不使用TextView,而是使用EditText接受用户的输入:

<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);
// do your calculations here and other stuffs
} catch (Exception e) {
e.printStackTrace();
}
} else {
// show empty input message
}

最新更新