Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.example.dave.temperatureconverter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Spinner spinnerInputUnit;
EditText txtInput;
TextView resultCelcius;
TextView resultFaren;
TextView resultKelvin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerInputUnit = (Spinner) findViewById(R.id.spinnerInputUnit);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.units_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinnerInputUnit.setAdapter(adapter);
txtInput = (EditText) findViewById(R.id.txtInput);
resultCelcius = (TextView) findViewById(R.id.resultCelcius);
resultFaren = (TextView) findViewById(R.id.resultFaren);
resultKelvin = (TextView) findViewById(R.id.resultKelvin);
}
public void convert(View v) {
double inputValue = Double.valueOf(txtInput.getText().toString());
String inputUnit = spinnerInputUnit.getSelectedItem().toString();
switch(inputUnit) {
case "Celcius":
resultCelcius.setText(Double.toString(inputValue));
resultFaren.setText(Double.toString(inputValue * 1.8 + 32));
resultKelvin.setText(Double.toString(inputValue + 273.15));
break;
case "Farenheit":
resultCelcius.setText(Double.toString((inputValue -32) * 5 / 9));
resultFaren.setText(Double.toString(inputValue));
resultKelvin.setText(Double.toString((inputValue + 459.67) * 5 / 9));
break;
case "Kelvin":
resultCelcius.setText(Double.toString(inputValue - 273.15));
resultFaren.setText(Double.toString(inputValue * 9 / 5 - 459.67));
resultKelvin.setText(Double.toString(inputValue));
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.