Android Toolbar “Up” Arrow in custom implementatio

2019-08-05 04:13发布

I am making a very custom Toolbar (don't freak, it's for good, not evil, I promise), and I want to put the "Up" arrow (the arrow that appears when there is a parent Activity set or for other reasons and has the nice ripple touch effect on Lollipop) in a custom location.

Is there a way to get this arrow as a View or asset to use somewhere else in the Toolbar?

I could not even find the image asset for the arrow. Any ideas?

For an example, I want top be able to do something like:

mToolbar.addView(arrowView, 0);
mToolbar.addView(titleView, 1);

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-05 04:37

If you don't want to place arrow icon as custom view in Toolbar, alternatively you can set content description to the navigation button and find view reference later. Every View or ViewGroup supports finding views with content description.

public static View getNavigationIcon(Toolbar toolbar){
    //check if contentDescription previously was set
    boolean hadContentDescription = TextUtils.isEmpty(toolbar.getNavigationContentDescription());
    String contentDescription = !hadContentDescription ? toolbar.getNavigationContentDescription() : "navigationIcon";
    toolbar.setNavigationContentDescription(contentDescription);
    ArrayList<View> potentialViews = new ArrayList<View>();
    //find the view based on it's content description, set programatically or with android:contentDescription
    toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
    //Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence 
    View navIcon = null;
    if(potentialViews.size() > 0){
        navIcon = potentialViews.get(0); //navigation icon is ImageButton
    }
     //Clear content description if not previously present
    if(hadContentDescription)
        toolbar.setNavigationContentDescription(null);
    return navIcon;
 }
查看更多
迷人小祖宗
3楼-- · 2019-08-05 04:42

Toolbar is itself a ViewGroup were you can add different views for eg.

<android.support.v7.widget.Toolbar
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar" >

     <TextView ..../>
     <ImageView ...../>
</android.support.v7.widget.Toolbar>

Refer your toolbar and its elements from your java code to have control over it as:

Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
ImageView img = (ImageView) toolbar.findViewById(R.id.imgv);
查看更多
冷血范
4楼-- · 2019-08-05 04:47

Maybe this will help, looks like something that you want, or you want completely custom up button with different position and view?

查看更多
登录 后发表回答