Kotlin for Android Developers
Download 1.04 Mb. Pdf ko'rish
|
Kotlin for Android Developers Learn Kotlin the Easy Way While Developing an Android App ( PDFDrive )
- Bu sahifa navigatsiya:
- 26.1 Creating the settings activity
26 Settings Screen
Until now, we’ve been using a default city to implement the App, but it’s time add the ability to select a city. Our App needs a settings section where the user can change the city. We are going to stick to the zip code to identify the city. A real App would probably need more information, because a zip code by itself doesn’t identify a city in the whole world. But we at least will show a city around the world that uses the zip code we are defining in settings. This will be a good example to explain an interesting way to deal with preferences. 26.1 Creating the settings activity A new activity will we opened when the settings option is selected in the overflow menu in the toolbar. So first thing we need is a new SettingsActivity : 1 class SettingsActivity : AppCompatActivity() { 2 3 override fun onCreate(savedInstanceState: Bundle?) { 4 super.onCreate(savedInstanceState) 5 setContentView(R.layout.activity_settings) 6 setSupportActionBar(toolbar) 7 supportActionBar?.setDisplayHomeAsUpEnabled(true) 8 } 9 10 override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { 11 android.R.id.home -> { onBackPressed(); true } 12 else -> false 13 } 14 } We’ll save the preference when the user gets out of the screen activity, so we’re going to deal with the Up action the same way as the Back one, by redirecting the action to onBackPressed . By now, let’s create the XML layout. A simple EditText will be enough for the preference: 126 26 Settings Screen 127 1 xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent"> 5 6 7 8 android:orientation="vertical" 10 android:layout_width="match_parent" 11 android:layout_height="match_parent" 12 android:layout_marginTop="?attr/actionBarSize" 13 android:padding="@dimen/spacing_xlarge"> 14 15 android:layout_width="wrap_content" 17 android:layout_height="wrap_content" 18 android:text="@string/city_zipcode"/> 19 20 android:id="@+id/cityCode" 22 android:layout_width="match_parent" 23 android:layout_height="wrap_content" 24 android:hint="@string/city_zipcode" 25 android:inputType="number"/> 26 27 28 29 And then just declare the activity in the AndroidManifest.xml : 1 android:name=".ui.activities.SettingsActivity" 3 android:label="@string/settings"/> Download 1.04 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling