In my app, there is an activity which needs to be closed on navigation click. In the past, the code below worked perfectly, however, since the new Android changes it doesnt work anymore.
Are there new ways to call the Navigation icon click? Is there something i am missing?
ActivitySettings.kt
class ActivitySettings : AppCompatActivity() {
private lateinit var binder: ActivitySettingsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binder = ActivitySettingsBinding.inflate(layoutInflater)
setContentView(R.layout.activity_settings)
binder.topToolbarBack.setNavigationOnClickListener {
finish()
}
}
}
activity_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/topToolbarBack"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:navigationIconTint="@color/white_material"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navigationIcon="@drawable/ic_outline_arrow_back_24"
app:popupTheme="@style/popupMenuThemeDark"
app:title="@string/currentScreenSettings"
app:titleTextColor="@color/white_material" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvSettings"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/topToolbarBack" />
</androidx.constraintlayout.widget.ConstraintLayout>
This problem is caused by the way the layouts got called.
binder
can be considered a "secondary layout". Since in that activity, i set as ContenteView R.layout.activity_settings
, the binder, that can still get the elements from the layout, gets basically covered by the layout currently set.
If you want to use binder
you must set as inside setContentView()
binder.root
, which loads the proper layout you need.
So, the code fixed is:
class ActivitySettings : AppCompatActivity() {
private lateinit var binder: ActivitySettingsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binder = ActivitySettingsBinding.inflate(layoutInflater)
setContentView(binder.root)
binder.topToolbarBack.setNavigationOnClickListener {
finish()
}
}
}