In a Compose application, I implemented the Settings screen as a new AppCompatActivity
containing my PreferenceFragment
.
In order to navigate between screens in Compose and the Preference Activity, I use intents.
I added a Toolbar with a left arrow icon to the AppCompatActivity, not linked to any NavController:
Settings Activity
override fun onCreate(savedInstanceState: Bundle?) {
... // replace content view with PreferenceFragment
val toolbar = findViewById<MaterialToolbar>(R.id.toolbar)
toolbar.setOnClickListener {
val intent = Intent(context, MainActivity::class.java))
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
}
Layout of Settings Activity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:navigationIcon="@drawable/baseline_arrow_back_24"
app:title="@string/settings" />
<FrameLayout
android:id="@+id/settings"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This approach works, but has 2 problems:
Adding setNavigationOnClickListener
for toolbar will stop toolbar for getting clicked so, remaining part of the toolbar
will not be clickable, and the user will be able to only click on the icon for navigation
. Also this will show ripple effect
for the navigation icon.
You can try this below code :
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
val toolbar = findViewById<MaterialToolbar>(R.id.toolbar)
//This line is important else listener won't work
setSupportActionBar(toolbar)
// Enable back navigation icon
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
// Set click listener for navigation icon
toolbar.setNavigationOnClickListener {
val intent = Intent(this, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
// When user selects a menu item
toolbar.setOnMenuItemClickListener {
when (it.itemId) {
R.id.action_settings -> {
// Navigate to settings screen.
true
}
R.id.action_done -> {
// Save profile changes.
true
}
else -> false
}
}
}
}
Reference link :