How to get the up button that is used on the toolbar?

This is a short question:

I am trying to force the action bar (used by the toolbar) to use LTR alignment. I managed to make the layout itself using LTR, but not the up button (as I did here before the Toolbar ).

This view seems to have no identifier, and I think using getChildAt () is too risky.

Can anyone help?


Answer

Here is one way to find a solution based on this answer .

I made sure that only the up button is guaranteed to be found, and whatever she does, she will return to her previous state, which was earlier.

Here is the code:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public boolean onCreateOptionsMenu(final Menu menu) { // <= do the normal stuff of action bar menu preparetions if(VERSION.SDK_INT>=VERSION_CODES.JELLY_BEAN_MR1&&getResources().getConfiguration().getLayoutDirection()==View.LAYOUT_DIRECTION_RTL) { final ArrayList<View> outViews=new ArrayList<>(); final CharSequence previousDesc=_toolbar.getNavigationContentDescription(); for(int id=0;;++id) { final String uniqueContentDescription=Integer.toString(id); _toolbar.findViewsWithText(outViews,uniqueContentDescription,View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); if(!outViews.isEmpty()) continue; _toolbar.setNavigationContentDescription(uniqueContentDescription); _toolbar.findViewsWithText(outViews,uniqueContentDescription,View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); if (outViews.isEmpty()) if (BuildConfig.DEBUG) throw new RuntimeException( "You should call this function only when the toolbar already has views"); else break; outViews.get(0).setRotation(180f); break; } _toolbar.setNavigationContentDescription(previousDesc); } // return super.onCreateOptionsMenu(menu); } 
+5
source share
1 answer

This view does not seem to have an identifier

You are right, the navigation view is created programmatically and never sets an id. But you can still find it using View.findViewsWithText .

View.findViewsWithText comes with two flags:

The default content description for the Navigation Up navigation view or the resource identifier abc_action_bar_up_description for AppCompat and action_bar_up_description for the framework, but you can easily apply your own use of Toolbar.setNavigationContentDescription .

Here is an example implementation:

 final Toolbar toolbar = ...; toolbar.setNavigationContentDescription("up"); setActionBar(toolbar); final ArrayList<View> outViews = Lists.newArrayList(); toolbar.findViewsWithText(outViews, "up", View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); outViews.get(0).setRotation(180f); 

results

example

+6
source

Source: https://habr.com/ru/post/1207823/


All Articles