美文网首页
setSupportActionBar

setSupportActionBar

作者: 有点健忘 | 来源:发表于2018-07-25 17:45 被阅读1437次

现在是在xml写一个 toolbar,完事代码里 setSupportActionBar(toolbar)
实际使用中应该会发现,xml里toolbar里如果你添加了一些view,这些view的最左边并不是屏幕的左边缘。

toolbar代码如下,我给textview弄了个背景

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_collapseMode="pin"
                    android:paddingTop="24dp"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

                    <TextView
                        android:id="@+id/tv_title"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:gravity="center"
                        android:text="title"
                        android:background="#44000000"
                        android:textColor="#fff" />

                    <ImageView
                        android:layout_width="30dp"
                        android:layout_height="30dp"
                        android:layout_gravity="center_vertical|right"
                        android:src="@mipmap/ic_launcher_round" />
                </android.support.v7.widget.Toolbar>

如图所示,可以看到阴影距离左边是有一段距离的。


image.png

一路点进去,可以发现在AppCompatDelegateImplV9类里setSupportActionBar的具体实现
代码如下

    public void setSupportActionBar(Toolbar toolbar) {
      //省略部分代码
        if (toolbar != null) {
            final ToolbarActionBar tbab = new ToolbarActionBar(toolbar,
                    ((Activity) mOriginalWindowCallback).getTitle(), mAppCompatWindowCallback);
            mActionBar = tbab;
            mWindow.setCallback(tbab.getWrappedWindowCallback());
        } else {
            mActionBar = null;
            // Re-set the original window callback since we may have already set a Toolbar wrapper
            mWindow.setCallback(mAppCompatWindowCallback);
        }

        invalidateOptionsMenu();
    }

上边代码可以看出,new了一个ToolbarActionBar,继续往下走

    ToolbarActionBar(Toolbar toolbar, CharSequence title, Window.Callback windowCallback) {
        mDecorToolbar = new ToolbarWidgetWrapper(toolbar, false);
        mWindowCallback = new ToolbarCallbackWrapper(windowCallback);
        mDecorToolbar.setWindowCallback(mWindowCallback);
        toolbar.setOnMenuItemClickListener(mMenuClicker);
        mDecorToolbar.setWindowTitle(title);
    }

这里又new了一个ToolbarWidgetWrapper的东西
然后在构造方法里发现了这样的属性,看名字很像

final TintTypedArray a = TintTypedArray.obtainStyledAttributes(toolbar.getContext(),
                    null, R.styleable.ActionBar, R.attr.actionBarStyle, 0);

     final int contentInsetStart = a.getDimensionPixelOffset(
                    R.styleable.ActionBar_contentInsetStart, -1);
            final int contentInsetEnd = a.getDimensionPixelOffset(
                    R.styleable.ActionBar_contentInsetEnd, -1);
            if (contentInsetStart >= 0 || contentInsetEnd >= 0) {
                mToolbar.setContentInsetsRelative(Math.max(contentInsetStart, 0),
                        Math.max(contentInsetEnd, 0));
            }

试着在xml里contentInsetStart=0dp发现那个偏移没了,那应该就是了。

顺道看下默认值

我用的v7 27的版本,在design库的res的values下找

<item name="contentInsetStart">@dimen/abc_action_bar_content_inset_material</item>
      <item name="contentInsetStartWithNavigation">@dimen/abc_action_bar_content_inset_with_nav</item>
      <item name="contentInsetEnd">@dimen/abc_action_bar_content_inset_material</item>

<dimen name="abc_action_bar_content_inset_material">16dp</dimen>
  <dimen name="abc_action_bar_content_inset_with_nav">72dp</dimen>

我们还是回到toolbar看下,他的layout是咋处理这些控件的

 protected void onLayout(boolean changed, int l, int t, int r, int b){
//省略。。这里只考虑默认的布局从左到右,不考虑从右到左的布局
        if (shouldLayout(mNavButtonView)) {
            if (isRtl) {
                right = layoutChildRight(mNavButtonView, right, collapsingMargins,
                        alignmentHeight);
            } else {
//可以看到默认是加在左边的,而且是第一个添加的
                left = layoutChildLeft(mNavButtonView, left, collapsingMargins,
                        alignmentHeight);
            }
        }

        if (shouldLayout(mMenuView)) {
            if (isRtl) {
                left = layoutChildLeft(mMenuView, left, collapsingMargins,
                        alignmentHeight);
            } else {
//可以看到menu里的东西默认是添加在右边的。
                right = layoutChildRight(mMenuView, right, collapsingMargins,
                        alignmentHeight);
            }
        }
  //这里处理了一下contentinsetleft和right
final int contentInsetLeft = getCurrentContentInsetLeft();
        final int contentInsetRight = getCurrentContentInsetRight();
        collapsingMargins[0] = Math.max(0, contentInsetLeft - left);
        collapsingMargins[1] = Math.max(0, contentInsetRight - (width - paddingRight - right));
        left = Math.max(left, contentInsetLeft);
//其实可以看到,如果上边有back按钮的话,那个left肯定很大了,这里其实contentinsetleft就没啥用了。
        right = Math.min(right, width - paddingRight - contentInsetRight);

//可以看到下边的都是左边的
        if (shouldLayout(mExpandedActionView)) {
            if (isRtl) {
            } else {
                left = layoutChildLeft(mExpandedActionView, left, collapsingMargins,
                        alignmentHeight);
            }
        }
  //添加到左边
        if (shouldLayout(mLogoView)) {
            if (isRtl) {
            } else {
                left = layoutChildLeft(mLogoView, left, collapsingMargins,
                        alignmentHeight);
            }
        }
//省略title。logo之类的添加代码

//最后才是添加我们在toolbar里添加的view,也就是customview拉,比如开头的toolbar里添加的textview和imagview
 // Get all remaining children sorted for layout. This is all prepared
        // such that absolute layout direction can be used below.

        addCustomViewsWithGravity(mTempViews, Gravity.LEFT);//循环找到gravity设置为left的view
        final int leftViewsCount = mTempViews.size();
        for (int i = 0; i < leftViewsCount; i++) {
//把这些重心在left的添加到左边
            left = layoutChildLeft(mTempViews.get(i), left, collapsingMargins,
                    alignmentHeight);
        }

        addCustomViewsWithGravity(mTempViews, Gravity.RIGHT);//循环找到gravity设置为right的view
        final int rightViewsCount = mTempViews.size();
        for (int i = 0; i < rightViewsCount; i++) {
  //把这些重心为right的,从右边开始添加
            right = layoutChildRight(mTempViews.get(i), right, collapsingMargins,
                    alignmentHeight);
        }

        // Centered views try to center with respect to the whole bar, but views pinned
        // to the left or right can push the mass of centered views to one side or the other.
//最后添加其他没有设置重心为left和right的,
        addCustomViewsWithGravity(mTempViews, Gravity.CENTER_HORIZONTAL);
        final int centerViewsWidth = getViewListMeasuredWidth(mTempViews, collapsingMargins);
        final int parentCenter = paddingLeft + (width - paddingLeft - paddingRight) / 2;
        final int halfCenterViewsWidth = centerViewsWidth / 2;
        int centerLeft = parentCenter - halfCenterViewsWidth;
        final int centerRight = centerLeft + centerViewsWidth;
        if (centerLeft < left) {
            centerLeft = left;
        } else if (centerRight > right) {
            centerLeft -= centerRight - right;
        }

        final int centerViewsCount = mTempViews.size();
        for (int i = 0; i < centerViewsCount; i++) {
            centerLeft = layoutChildLeft(mTempViews.get(i), centerLeft, collapsingMargins,
                    alignmentHeight);
        }
}

总结,对于toolbar里边的内容是自定义的情况,如果不用系统的后退按钮的话,去除那个默认偏移量的话

在代码里添加

app:contentInsetStart="0dp" 或者app:contentInsetLeft="0dp"

原本以为好了,结果发现6.0的机器上还是有个padding,而在8.0的机器是没有padding的
好奇怪,如下图

image.png

那就看下是不是有默认的padding
``
public Toolbar(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.toolbarStyle);
}
//去values下找

 <item name="android:paddingLeft">@dimen/abc_action_bar_default_padding_start_material</item>
        <item name="android:paddingRight">@dimen/abc_action_bar_default_padding_end_material</item>

完事在27的版本中找到的结果

 <dimen name="abc_action_bar_default_padding_end_material">0dp</dimen>
    <dimen name="abc_action_bar_default_padding_start_material">0dp</dimen>

现在有点晕啊,这些东西都是v7库里的东西,不管运行在6.0的手机还是8.0的手机,这个库应该没区别啊,按理数据是一样的啊,太奇怪了。
后来突然醒悟过来,我6.0的测试机是个平板,以我多年的经验,平板和手机有些数据是有区别的。。。
果不其然,我找到这个资源目录values-sw600dp-v13
在下边发现了,我擦,平板默认是有个padding的。

<dimen name="abc_action_bar_default_padding_end_material">8dp</dimen>
    <dimen name="abc_action_bar_default_padding_start_material">8dp</dimen>

这让我想起以前重写Tablayout的时候也是被平板坑了,平板的tabgravity默认是center的。

简单总结下

Toolbar 通过 setSupportActionBar(toolbar) 被修饰成了actionbar。
Toolbar里的布局问题,整体和线性布局差不多,一个挨一个的,从左加,从右加。
默认的返回按钮,title之类的都在左侧,menu的东西都从右侧添加
至于在toolbar里添加的其他view,首先按照view的gravity是left还是right添加,left的从左侧添加,right的从右侧添加。
其他的view是从left开始添加的,
toolbar在平板上是有个默认的8dp的paddingleft和right的。

相关文章

网友评论

      本文标题:setSupportActionBar

      本文链接:https://www.haomeiwen.com/subject/lbbpmftx.html