В настоящее время я пытаюсь выяснить, как я могу увидеть значение переменной редактирования текста.В своем коде я пытаюсь взять введенный пользователем номер и применить к нему математику, чтобы получить калькулятор чаевых.Единственная проблема заключается в том, что, если пользователь не ввел никаких значений для переменной Edit Text для инициализации, значение переменной Edit Text не является нулевым или даже пустой строкой, а содержит абсурдно длинную строку кода, приведенную здесь: android.support.v7.widget.AppCompatEditText {1b372dd VFED..CL.......Я.0,0-0,0 # 7f07009b app: id / userInput}
Это значение переменной Edit Text с именем userInputAmount, которая была инициализирована с помощью метода findViewById с параметрами (R.id.userInput)
Однако ошибка возникает , когда я пытаюсь связать значение этой переменной Edit Text userInputAmount с двойным значением userAmount с помощьюметод Double.parseDouble с параметрами (userInputAmount.getText (). toString ())
Причина, по которой мне нужно на самом деле определить значение EditText, заключается в том, что я могу создать логический вентиль, который обходитдвойное преобразование, чтобы оно не зависало в моем приложении.
Я хотел бы сделать следующее:
if(editTextVariable != null && editTextVariable != "")
//Do the double conversion
else
//set the double variable equal to 0 so it wont crash the app.
TLDR: мне нужно выяснить значение текста редактирования, чтобы создатьлогический элемент для обхода преобразования, если значение равно android.support.v7.widget.AppCompatEditText {1b372dd VFED..CL.......Я.0,0-0,0 # 7f07009b app: id / userInput} Я бы также предпочел не инициализировать переменную редактирования текста, если это значение имеет значение.Я думал, может быть, проверить значение ссылки XML (userInput) с оператором if перед инициализацией, но я не знаю, как это сделать.
Ошибка возникает с этим оператором
userAmount = Double.parseDouble(userInputAmount.getText().toString());
Ниже приведен код и xml
package com.example.frankbuddy.advancedtipcalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Color;
public class MainActivity extends AppCompatActivity {
SeekBar tipSeekBar;
int seekBarValue;
//For custom tip percentage ($%)
TextView tipDisplay;
//For applied custom percentage to user input (#.#$)
TextView tipAmountDisplay;
//For 15% tip
TextView defTipAmount;
//For Default 15% tip total amount
TextView defTotalAmount;
//For Custom % tip total amount
TextView mainTotalAmount;
//For user input amount
EditText userInputAmount;
double userAmount;
double defaultTip;
double defaultTotal;
double userTotalTip;
double userCustomTotal;
private final int ORANGE = 0xFFFF3300;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize custom percentage display amount
tipDisplay = (TextView) findViewById(R.id.tipDisplayPercentage);
//Intialize user input amount edit text
userInputAmount =(EditText)findViewById(R.id.userInput);
//Initialize tip amount display
tipAmountDisplay = (TextView)findViewById(R.id.tipDisplayAmount);
//Initialize default tip amount
defTipAmount = (TextView)findViewById(R.id.defaultTipAmount);
//Initialize default total amount
defTotalAmount = (TextView)findViewById(R.id.defaultTotalAmount);
//Initialize custom total amount
mainTotalAmount = (TextView)findViewById(R.id.customTotalAmount);
userTotalTip = 0.0;
userCustomTotal = 0.0;
defaultTotal = 0;
defaultTip = 0;
userAmount = 0;
//Seek Bar initialize
tipSeekBar = (SeekBar)findViewById(R.id.seekBar);
tipSeekBar.setMax(100);
tipSeekBar.setProgress(15);
//Display initial custom tip amount (Default 15%)
tipDisplay.setTextColor(Color.GREEN);
tipDisplay.setText(tipSeekBar.getProgress() + "%");
//Seek bar listener
tipSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
//initialize progress value (To be used for display and math)
int progressChangedValue = 0;
//Realtime listener for updates
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
//Set progress changed value
progressChangedValue = progress ;
//Update custom display percentage amount
tipDisplay.setText(progressChangedValue + "%");
if(progressChangedValue <= 20)
{
tipDisplay.setTextColor(Color.GREEN);
}
if(progressChangedValue >= 21 && progressChangedValue <= 29)
{
tipDisplay.setTextColor(Color.YELLOW);
}
//Display warning if progress value meets or exceeds 30%
if(progressChangedValue >= 30)
{
Toast.makeText(MainActivity.this, "Warning, Tip is now exceeding 30% and the value is now " + progressChangedValue + "%",
Toast.LENGTH_SHORT).show();
tipDisplay.setTextColor(Color.RED);
}
//Bind user input amount into a double variable to apply mathematics
userAmount = Double.parseDouble(userInputAmount.getText().toString());
//Do math for custom tip amount
userTotalTip = userAmount * progressChangedValue *.01;
tipAmountDisplay.setText(String.format("%.2f", userTotalTip));
//Do math for custom total amount
userCustomTotal = userTotalTip + userAmount;
mainTotalAmount.setText(String.format("%.2f", userCustomTotal));
//Do math for default tip amount
defaultTip = userAmount * .15;
defTipAmount.setText(String.format("%.2f", defaultTip));
//Do math for default total amount
defaultTotal = defaultTip + userAmount;
defTotalAmount.setText(String.format("%.2f",defaultTotal ));
}
//Listener for first changes
public void onStartTrackingTouch(SeekBar seekBar)
{
}
//Listener for when the user stops manipulating the bar
public void onStopTrackingTouch(SeekBar seekBar)
{
}
});
}
И XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
tools:context=".MainActivity">
<TextView
android:id="@+id/tipDisplayAmount"
android:layout_width="76dp"
android:layout_height="31dp"
android:layout_marginStart="8dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="8dp"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.555"
app:layout_constraintStart_toEndOf="@+id/defaultTipAmount"
app:layout_constraintTop_toBottomOf="@+id/tipDisplayPercentage" />
<TextView
android:id="@+id/textView4"
android:layout_width="123dp"
android:layout_height="31dp"
android:layout_marginStart="20dp"
android:layout_marginTop="24dp"
android:layout_marginBottom="8dp"
android:text="Total"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3"
app:layout_constraintVertical_bias="0.011" />
<TextView
android:id="@+id/textView"
android:layout_width="125dp"
android:layout_height="35dp"
android:layout_marginStart="8dp"
android:layout_marginTop="120dp"
android:layout_marginEnd="8dp"
android:text="Amount $"
android:textAlignment="center"
android:textSize="26sp"
app:layout_constraintEnd_toStartOf="@+id/userInput"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="127dp"
android:layout_height="35dp"
android:layout_marginStart="16dp"
android:layout_marginTop="28dp"
android:text="Custom %"
android:textAlignment="center"
android:textSize="26sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<EditText
android:id="@+id/userInput"
android:layout_width="207dp"
android:layout_height="42dp"
android:layout_marginEnd="16dp"
android:layout_marginTop="112dp"
android:ems="10"
android:hint="0.00"
android:inputType="numberDecimal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="209dp"
android:layout_height="35dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="8dp"
android:layout_marginTop="28dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toEndOf="@+id/textView2"
app:layout_constraintTop_toBottomOf="@+id/userInput" />
<TextView
android:id="@+id/textView3"
android:layout_width="123dp"
android:layout_height="31dp"
android:layout_marginStart="16dp"
android:layout_marginTop="56dp"
android:text="Tip"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<TextView
android:id="@+id/textView5"
android:layout_width="76dp"
android:layout_height="31dp"
android:layout_marginStart="168dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="15%"
android:textAlignment="center"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="@+id/textView3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2"
app:layout_constraintVertical_bias="0.666" />
<TextView
android:id="@+id/tipDisplayPercentage"
android:layout_width="76dp"
android:layout_height="31dp"
android:layout_marginStart="8dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="8dp"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.583"
app:layout_constraintStart_toEndOf="@+id/textView5"
app:layout_constraintTop_toBottomOf="@+id/seekBar" />
<TextView
android:id="@+id/defaultTipAmount"
android:layout_width="76dp"
android:layout_height="31dp"
android:layout_marginStart="32dp"
android:layout_marginTop="12dp"
android:textAlignment="center"
android:textSize="18sp"
app:layout_constraintStart_toEndOf="@+id/textView3"
app:layout_constraintTop_toBottomOf="@+id/textView5" />
<TextView
android:id="@+id/defaultTotalAmount"
android:layout_width="73dp"
android:layout_height="31dp"
android:layout_marginStart="28dp"
android:layout_marginTop="24dp"
android:layout_marginBottom="8dp"
android:textAlignment="center"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="@+id/textView4"
app:layout_constraintTop_toBottomOf="@+id/defaultTipAmount"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="@+id/customTotalAmount"
android:layout_width="76dp"
android:layout_height="31dp"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="28dp"
android:layout_marginBottom="8dp"
android:textAlignment="center"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.535"
app:layout_constraintStart_toEndOf="@+id/defaultTotalAmount"
app:layout_constraintTop_toBottomOf="@+id/tipDisplayAmount"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>