Puste pole: walidacja
Dane od użytkownika: EditText - Aplikacje mobilne: Android krok po kroku (android)
Ta sama aplikacja, ale z walidacją: `trim()` obcina spacje, `isEmpty()` sprawdza, czy coś zostało, a `return` kończy obsługę kliknięcia przed obliczeniami. Zamiast awarii użytkownik widzi podpowiedź w Toaście. Tak samo warto chronić każde pole liczbowe.
{"layout":"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\">\n\n <EditText\n android:id=\"@+id/number\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Liczba\"\n android:inputType=\"number\" />\n\n <Button\n android:id=\"@+id/square\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Kwadrat\" />\n\n <TextView\n android:id=\"@+id/result\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"\"\n android:textSize=\"20sp\" />\n\n</LinearLayout>\n","code":"package com.example.app;\n\nimport android.os.Bundle;\nimport android.widget.*;\nimport androidx.appcompat.app.AppCompatActivity;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n EditText number = findViewById(R.id.number);\n TextView result = findViewById(R.id.result);\n findViewById(R.id.square).setOnClickListener(v -> {\n String text = number.getText().toString().trim();\n if (text.isEmpty()) {\n Toast.makeText(this, \"Najpierw wpisz liczbę\", Toast.LENGTH_SHORT).show();\n return;\n }\n int n = Integer.parseInt(text);\n result.setText(n + \" do kwadratu to \" + (n * n));\n });\n }\n}\n"}Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu Aplikacje mobilne: Android krok po kroku·Zaloguj się, aby zapisać postęp na koncie.