8. Конвертер на Android
Первинні вкладки
1. Створіть новий проект в Android Studio.
2. Видаліть всі елементи активного екрану. Додайте дві RadioGroup(по дві RadioButton у кожній). Та додайте елемент EditText.
3. Редагуйте властивості елементів наступним чином:
у верхніх кнопок onClick: convertCMeters, convertMeter, convertKMeters;
id: bCmeters, bMeters & Checked, bKmeters;
у нижніх кнопок id: but1, but2 & Checked, but3.
4. Редагуйте властивості текстового поля: Input type -> numberSigned, numberDecimal.
5. У MainActivity додайте власні функції:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public float convertMtoKm(float meter) { //функція переведення метрів в кілометри return (float) (meter / 1000); } public float convertMtoCm(float meter) { //функція переведення метрів в сантиметри return (float) (meter * 100); } public float convertCmtoKm(float meter) { //функція переведення сантиметри в кілометри return (float) (meter / 10000); } public float convertKmtoCm(float meter) { //функція переведення кілометри в сантиметри return (float) (meter * 10000); } public float convertCmtoM(float meter) { //функція переведення сантиметрів в метри return (float) (meter / 100); } public float convertKmtoM(float meter) { //функція переведення кілометрів в метри return (float) (meter / 100); } public float convertKmtoKm(float meter) { //функції повернення поточного значення return (float) meter; } public float convertCmtoCm(float meter) { return (float) meter; } public float convertMtoM(float meter) { return (float) meter; } |
6. Оголосіть змінні та кнопки при створенні:
1 2 3 4 5 6 7 8 9 10 11 | public EditText mInput; // змінна текстового поля public RadioButton but1,but2,but3; // змінні кнопок, котрі перевіряються @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mInput = (EditText) findViewById(R.id.editText); but1 = (RadioButton)findViewById(R.id.CMeters); but2 = (RadioButton)findViewById(R.id.Meters); but3 = (RadioButton)findViewById(R.id.KMeters); } |
7. Напишіть код для кожної кнопки окремо(приклад для метрів, для кіло- та сантиметрів напишіть самі по аналогії):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public void convertMeters(View view) { if (mInput.getText().length() == 0) { Toast.makeText(getApplicationContext(), "Введіть довжину!", Toast.LENGTH_LONG).show(); return; } float inputValue = Float.parseFloat(mInput.getText().toString()); if (but1.isChecked()) { mInput.setText(String.valueOf(convertCmtoM(inputValue))); } else if(but3.isChecked()) { mInput.setText(String.valueOf(convertKmtoM(inputValue))); } else { mInput.setText(String.valueOf(convertMtoM(inputValue))); } } |
8. Запустіть на виконання. Результати:
Контрольні питання:
1. Опишіть загальний вигляд власної функції в java.
2. Як отримати вміст текстового поля у змінну?
3. Як можна отримати доступ до властивостей елемента у коді?