How do I specifically get the switch from my actionLayout (that is a menu item) so I can set the 'setOnCheckedChangeListener' event?
Here is my menu for the navigation drawer:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/nav_switch"
app:actionLayout="@layout/action_view_switch"
android:title="One-to-one mode" />
</menu>
With the action_view_switch actionlayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:id="@+id/otoSwitch"
android:layout_width="fill_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
And finally, my navigation drawer:
<android.support.design.widget.NavigationView
android:id="@+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
app:menu="@menu/drawer_view"
app:headerLayout="@layout/nav_header"/>
I understand that I can do something like:
Menu menu = navigationView.getMenu();
MenuItem menuItem = menu.findItem(R.id.nav_switch);
View actionView = MenuItemCompat.getActionView(menuItem);
actionView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
But this does not give me any states such as isChecked like 'setOnCheckedChangeListener' would. How do I get the switch view so I can set its listeners?
You've pretty much got it figured out, just a few more things. Here's what worked for me!
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:id="@+id/otoSwitch"
android:layout_width="fill_parent"
android:layout_height="match_parent"
/>
Next you get the view from the menu item.
Menu menu = navigationView.getMenu();
SwitchCompat actionView = (SwitchCompat) menu.findItem(R.id.nav_switch).getActionView().findViewById(R.id.ontoSwitch);
actionView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
The reason I have another findViewById after the getActionView is because the getActionView will return a LinearLayout View and our switch is inside the LinearLayout so we just find the view id from the current LinearLayout returned to us, thus findItem(R.id.nav_switch).getActionView().findView... Hopefully this will help
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.