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);
您将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