沉浸式状态栏,包括折叠布局的顶部显示到状态栏

1、一般沉浸式状态栏
a、在BaseActivity.java中设置一系列参数。

public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setImmersiveMode();
    }

    public void setImmersiveMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(getResources().getColor(R.color.white));
        }
    }
}

/**
     * 设置状态栏字体黑色
     *
     * 当页面TitleBar背景色是亮色时调用此方法,为暗色时调用setImmersiveMode()。
     *
     * 小米的MIUI和魅族的Flyme在Android 4.4之后各自提供了自家的修改方法,其他品牌只能在Android 6.0及以后才能修改。
     *
     * 经过查看用户分布(2018-02-23)Android 6.0之下占33.27%,小米用户6.69%,魅族用户1.08%。
     * 这样一看都没有必要对小米、魅族分别处理了,那就都统一到Android 6.0去设置吧。
     */
    public void setImmersiveDarkMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            //设置状态栏底色白色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(Color.TRANSPARENT);
            // 设置状态栏字体黑色
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
    }

关于修改状态栏字体颜色,参考我的另一篇博客
b、创建一个自己的ActionBar.java

package com.txhl.testapp.widget;

import android.content.Context;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.widget.Space;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.txhl.testapp.R;
import com.txhl.testapp.utils.ScreenUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by chenyingjie on 2019/3/4
 */
public class ActionBar extends LinearLayout {

    @BindView(R.id.backButton)
    FrameLayout backButton;
    @BindView(R.id.tvTitleBarName)
    TextView tvTitleBarName;
    @BindView(R.id.ivMore)
    ImageView ivMore;
    @BindView(R.id.tvMore)
    TextView tvMore;
    @BindView(R.id.more)
    FrameLayout more;
    @BindView(R.id.bottomLine)
    View bottomLine;
    @BindView(R.id.titleBarLayout)
    LinearLayout titleBarLayout;
    @BindView(R.id.space)
    Space mSpace;
    @BindView(R.id.ivBack)
    ImageView ivBack;


    public ActionBar(Context context) {
        this(context, null);
    }

    public ActionBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ActionBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater.from(context).inflate(R.layout.action_bar, this, true);
        ButterKnife.bind(this);
    }

    // 设置space高度为状态栏高度
    public ActionBar setImmersiveMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSpace.getLayoutParams().height = ScreenUtils.getStatusBarHeight(getContext());
        }
        return this;
    }

    // 标题
    public ActionBar setTitle(CharSequence title) {
        tvTitleBarName.setText(title);
        return this;
    }

    public ActionBar setTitle(CharSequence title, int textColor) {
        tvTitleBarName.setText(title);
        if (textColor != 0) {
            tvTitleBarName.setTextColor(getResources().getColor(textColor));
        }
        return this;
    }

    public ActionBar setTitle(int res) {
        tvTitleBarName.setText(res);
        return this;
    }

    public ActionBar setTitle(int res, int textColor) {
        tvTitleBarName.setText(res);
        if (textColor != 0) {
            tvTitleBarName.setTextColor(getResources().getColor(textColor));
        }
        return this;
    }

    // 设置主题背景
    public ActionBar setBarBackgrand(int res) {
        titleBarLayout.setBackgroundResource(res);
        return this;
    }

    // 底线可见性
    public ActionBar withoutBottomLine(boolean hasBottomLine) {
        bottomLine.setVisibility(hasBottomLine ? VISIBLE : INVISIBLE);
        return this;
    }

    // 设置右边图片
    public ActionBar setRightImage(int res) {
        tvMore.setVisibility(GONE);
        ivMore.setVisibility(VISIBLE);
        ivMore.setImageResource(res);
        return this;
    }

    // 右边点击
    public ActionBar setOnRightButtonClickListener(OnClickListener onRightButtonClickListener) {
        more.setVisibility(VISIBLE);
        more.setOnClickListener(onRightButtonClickListener);
        return this;
    }

    // 设置左边图片
    public ActionBar setLeftImage(int res) {
        ivBack.setImageResource(res);
        ivBack.getLayoutParams().width = ivBack.getLayoutParams().height = ScreenUtils.dip2px(getContext(), 18f);
        return this;
    }

    // 左边点击
    public ActionBar setOnLeftButtonClickListener(OnClickListener onLeftButtonClickListener) {
        backButton.setOnClickListener(onLeftButtonClickListener);
        return this;
    }

    // 设置右文本
    public ActionBar setRightText(int res) {
        tvMore.setVisibility(VISIBLE);
        ivMore.setVisibility(GONE);
        tvMore.setText(res);
        return this;
    }
    public ActionBar setRightText(int res, int textColor) {
        tvMore.setVisibility(VISIBLE);
        ivMore.setVisibility(GONE);
        tvMore.setText(res);
        if (textColor != 0) {
            tvMore.setTextColor(getResources().getColor(textColor));
        }
        return this;
    }
    public ActionBar setRightText(CharSequence text) {
        tvMore.setVisibility(VISIBLE);
        ivMore.setVisibility(GONE);
        tvMore.setText(text);
        return this;
    }
    public ActionBar setRightText(CharSequence text, int textColor) {
        tvMore.setVisibility(VISIBLE);
        ivMore.setVisibility(GONE);
        tvMore.setText(text);
        if (textColor != 0) {
            tvMore.setTextColor(getResources().getColor(textColor));
        }
        return this;
    }


}

action_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/titleBarLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.widget.Space
        android:id="@+id/space"
        android:layout_width="match_parent"
        android:layout_height="0dp" />
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="44dp">
        <FrameLayout
            android:id="@+id/backButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:paddingLeft="13dp"
            android:paddingRight="13dp">

            <ImageView
                android:id="@+id/ivBack"
                android:layout_gravity="center_vertical"
                android:layout_width="8dp"
                android:layout_height="16dp"
                />
        </FrameLayout>

        <TextView
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:id="@+id/tvTitleBarName"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:gravity="center_vertical"
            android:textColor="@color/white"
            android:singleLine="true"
            android:ellipsize="end"
            android:textSize="16sp"
            tools:text="@string/app_name"
            />

        <FrameLayout
            android:id="@+id/more"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:paddingLeft="12dp"
            android:paddingRight="12dp"
            android:layout_alignParentRight="true"
            android:visibility="invisible"
            >
            <ImageView
                android:id="@+id/ivMore"
                android:layout_width="45dp"
                android:layout_height="33dp"
                android:visibility="visible"
                android:layout_gravity="center"
                />
            <TextView
                android:id="@+id/tvMore"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="13sp"
                android:layout_gravity="center"
                android:text=""
                android:visibility="gone"
                />
        </FrameLayout>


    </RelativeLayout>

    <View
        android:id="@+id/bottomLine"
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="@color/gray" />

</LinearLayout>

c、创建MyActivity继承BaseActivity,在布局中引用,配置文件中的style设置为NoActionBar,初始化之后设置ActionBar的样式即可。

2、CoordinatorLayout+沉浸式
使用CoordinatorLayout实现折叠头部,让头部填充状态栏实现沉浸式,上图:
在这里插入图片描述
上一篇 已经介绍过CoordinatorLayout实现折叠效果,这里直接上代码

activity:

package com.txhl.testapp.act.coordinator;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;

import com.txhl.testapp.R;
import com.txhl.testapp.act.BaseActivity;
import com.txhl.testapp.listener.AppBarStateChangeListener;
import com.txhl.testapp.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CoordinatorActivity extends BaseActivity {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.ivTop)
    ImageView ivTop;
    @BindView(R.id.toolBar)
    Toolbar toolBar;
    @BindView(R.id.collapsingToolbarLayout)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.appBarLayout)
    AppBarLayout appBarLayout;

    private int padding = 0;

    private List<String> tabLists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coordinator);
        ButterKnife.bind(this);

        tabLists.add("主页");
        tabLists.add("聊天");
        tabLists.add("联系人");
        tabLists.add("设置");

        // 没有此代码 toolBar的title不居中
        setSupportActionBar(toolBar);
        // 设置上边距为状态栏高度,这个高度就是关键所在。
        CollapsingToolbarLayout.LayoutParams layoutParams = (CollapsingToolbarLayout.LayoutParams) toolBar.getLayoutParams();
        layoutParams.topMargin = ScreenUtils.getStatusBarHeight(this);
        toolBar.setLayoutParams(layoutParams);

        appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {// 展开
                    toolBar.setNavigationIcon(null);
                } else if (state == State.COLLAPSED) {// 折叠
                    toolBar.setNavigationIcon(R.mipmap.arrow_back_white);
                } else if (state == State.IDLE) {// 中间

                }
            }
        });

        viewPager.setAdapter(new VPAdapter(getSupportFragmentManager(), tabLists));
        tabLayout.setupWithViewPager(viewPager);
    }

    class VPAdapter extends FragmentStatePagerAdapter {

        private List<String> list;

        public VPAdapter(FragmentManager fm, List<String> tabLists) {
            super(fm);
            list = tabLists;
        }

        @Override
        public Fragment getItem(int i) {
            return ItemFragment.newInstance(i, list.get(i));
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return list.get(position);
        }
    }
}

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".act.coordinator.CoordinatorActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:theme="@style/AppTheme.AppBarOverlay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbarLayout"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="@color/red"
            app:scrimVisibleHeightTrigger="150dp"
            app:collapsedTitleTextAppearance="@style/collapseditleTextAppearance"
            app:expandedTitleTextAppearance="@style/expandedTitleTextAppearance"
            app:toolbarId="@+id/toolBar"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/ivTop"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.5"
                android:src="@mipmap/img"
                android:adjustViewBounds="true"
                android:scaleType="fitXY" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolBar"
                app:layout_collapseMode="pin"
                app:title="ToolBar Title"
                app:popupTheme="@style/AppTheme.PopupOverlay"
                app:navigationIcon="@mipmap/daily_pressed"
                app:titleTextAppearance="@style/titleTextAppearance"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize">

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

        </android.support.design.widget.CollapsingToolbarLayout>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/white"
            app:tabIndicatorColor="#ff5000"
            app:tabIndicatorHeight="2dp"
            app:tabMode="fixed"
            app:tabSelectedTextColor="#ff5000"
            app:tabTextColor="@color/black">

        </android.support.design.widget.TabLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#aa000000" />
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

这里自定义了一个折叠监听:

package com.txhl.testapp.listener;

import android.support.design.widget.AppBarLayout;

/**
 * Created by chen.yingjie on 2019/4/1
 */
public abstract class AppBarStateChangeListener implements AppBarLayout.OnOffsetChangedListener {

    public enum State {
        EXPANDED,   // 展开
        COLLAPSED,  // 折叠
        IDLE        // 中间
    }

    private State mCurrentState = State.IDLE;

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
        if (i == 0) {
            if (mCurrentState != State.EXPANDED) {
                onStateChanged(appBarLayout, State.EXPANDED);
            }
            mCurrentState = State.EXPANDED;
        } else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) {
            if (mCurrentState != State.COLLAPSED) {
                onStateChanged(appBarLayout, State.COLLAPSED);
            }
            mCurrentState = State.COLLAPSED;
        } else {
            if (mCurrentState != State.IDLE) {
                onStateChanged(appBarLayout, State.IDLE);
            }
            mCurrentState = State.IDLE;
        }
    }

    public abstract void onStateChanged(AppBarLayout appBarLayout, State state);
}

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值