跳轉到其他 Activity

這是最常見的用法,將使用者引導到另一個頁面。

val btnGoToActivity = findViewById<Button>(R.id.btn_go_to_activity)
btnGoToActivity.setOnClickListener {
    startActivity(Intent(this, SecondActivity::class.java))
}

跳轉到設定頁面

當我們判別到 app 需要的功能沒有開啟,可以使用 AlertDialog 配合 Intent 來引導使用者開啟功能。

val btnGoToSetting = findViewById<Button>(R.id.btn_go_to_setting)
btnGoToSetting.setOnClickListener {
    startActivity(Intent(Settings.ACTION_SETTINGS))
}

其他常用設定頁面的常數如下:

Settings.ACTION_SETTINGS — 設定頁面

Settings.ACTION_AIRPLANE_MODE_SETTINGS — 飛航模式設定

Settings.ACTION_LOCATION_SOURCE_SETTINGS — 位置服務設定

完整的資料可以到 android.provider.Settings 查看

完整程式碼

MainActivity.xml

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btnGoToActivity = findViewById<Button>(R.id.btn_go_to_activity)
        btnGoToActivity.setOnClickListener {
            startActivity(Intent(this, SecondActivity::class.java))
        }

        val btnGoToSetting = findViewById<Button>(R.id.btn_go_to_setting)
        btnGoToSetting.setOnClickListener {
            startActivity(Intent(Settings.ACTION_SETTINGS))
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_go_to_activity"
        android:text="Go to Activity" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_go_to_setting"
        android:text="Go to Setting" />

</LinearLayout>

參考資料

android.provider.Settings

Last modified: 2022 年 9 月 27 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.