Android進(jìn)階之光——Material Design

Material Design

核心思想

Material Design的核心思想浪秘,就是將物理世界中的體驗(yàn)帶入屏幕,并且去掉物理世界中的雜志宝与,再配合虛擬世界的靈活特性梗醇,達(dá)到最貼近真實(shí)的體驗(yàn)。

Design Support Library 常用控件詳解

Snackbar

Snackbar顯示在屏幕的底部闯捎,包含了文字信息與一個(gè)可選的操作按鈕椰弊,它會(huì)在指定時(shí)間結(jié)束后消失。配合CoordinatorLayout使用瓤鼻,可以在超時(shí)之前將它劃動(dòng)刪除

  • build.gradle
    implementation 'com.android.support:design:28.0.0'

  • java
 Snackbar.make(activity_main,"SnackBar",Snackbar.LENGTH_LONG)
                .setAction("點(diǎn)擊事件", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "SnackBar的點(diǎn)擊事件", Toast.LENGTH_SHORT).show();
                    }
                }).setDuration(Snackbar.LENGTH_SHORT).show();

第一個(gè)參數(shù)是一個(gè)View類型的參數(shù)秉版,這個(gè)View類型的參數(shù)是Snackbar的父控件,還有兩個(gè)參數(shù) 一個(gè)是顯示的文本茬祷,一個(gè)是持續(xù)的時(shí)間清焕。setAction是設(shè)置點(diǎn)擊事件。

TextInputLayout

TextInputLayout是一個(gè)容器祭犯,和ScrollView一樣只接受一個(gè)子元素耐朴,并且這個(gè)子元素是EditText

  • xml布局文件
<androidx.constraintlayout.widget.ConstraintLayout 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=".TextInpuLayout">
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tl_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        >
        <EditText
            android:id="@+id/et_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="username"
            />
    </com.google.android.material.textfield.TextInputLayout>
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tl_userpwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/tl_username"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        >
        <EditText
            android:id="@+id/et_userpwd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="userpwd"
            />
    </com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

顯示錯(cuò)誤信息

 tlUserName.setErrorEnabled(true);
 tlUserName.setError("輸入錯(cuò)誤");

setErrorEnabled():用于顯示和隱藏錯(cuò)誤提示

FloatingActionButton

負(fù)責(zé)顯示界面基本操作的圓形按鈕№镌鳎可以當(dāng)作一個(gè)Button

  • xml
<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@android:color/holo_red_light"
        android:clickable="true"
        android:elevation="10dp"
        android:src="@drawable/ic_launcher"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/btn_login"
        app:pressedTranslationZ="100dp" />

FloatingActionButton的填充色默認(rèn)是style.xml文件的colorAccent設(shè)定的顏色筛峭,當(dāng)然也可以通過app:backgroundTint來設(shè)定背景填充色

  • app:elevation:用來設(shè)置正常狀態(tài)的陰影大小
  • app:pressedTranslationZ:用來設(shè)置點(diǎn)擊時(shí)陰影的大小

TabLayout實(shí)現(xiàn)類似網(wǎng)易選項(xiàng)卡的動(dòng)態(tài)滑動(dòng)效果

  • 配置build.gradle
implementation 'com.google.android.material:material:1.2.1'
  • 主頁面布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 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"
    android:orientation="vertical"
    tools:context=".NetEasyTabActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="#ADBE107E"
            app:tabMode="scrollable" />


    </com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    />
</androidx.appcompat.widget.LinearLayoutCompat>
  • list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</androidx.recyclerview.widget.RecyclerView>
  • list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <ImageView
        android:id="@+id/iv_item_card_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars"
        android:src="@drawable/sex"
        />

    <TextView
        android:id="@+id/tv_item_card_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="@id/iv_item_card_main"
        app:layout_constraintLeft_toRightOf="@id/iv_item_card_main"
        app:layout_constraintTop_toTopOf="@id/iv_item_card_main" />
</androidx.constraintlayout.widget.ConstraintLayout>

注意這里將TabLayout的app:tabMode="scrollable" 其設(shè)置Tab的模式為可滑動(dòng)的,還可以設(shè)置為fixed表示固定不可劃動(dòng)的

  • Java代碼
  • Activity

        for (String title : titles) {
            tabs.addTab(tabs.newTab().setText(title));
        }
        ArrayList<Fragment> fragments = new ArrayList<>();
        for (int i = 0; i < titles.size(); i++) {
            fragments.add(new ListFragment());
        }
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragments, titles);
        viewpager.setAdapter(fragmentAdapter);
        //TabLayout聯(lián)系ViewPager
        tabs.setupWithViewPager(viewpager);
    }
}
  • Fragment
public class ListFragment extends Fragment {

    private RecyclerView mRecycleView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRecycleView = ((RecyclerView) inflater.inflate(R.layout.list_fragment, container, false));
        return mRecycleView;
    }

    @Override
    public void onViewCreated(@NonNull @org.jetbrains.annotations.NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRecycleView.setLayoutManager(new LinearLayoutManager(mRecycleView.getContext()));
        mRecycleView.setAdapter(new RecycleViewAdapter(getActivity()));
    }
}
  • adapter FragmentAdapter
public class FragmentAdapter extends FragmentStatePagerAdapter {
    private List<Fragment> mFragments;
    private List<String> mTitles;
    public FragmentAdapter(@NonNull @NotNull FragmentManager fm, List<Fragment> fragments,List<String> titles) {
        super(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        mFragments = fragments;
        mTitles = titles;
    }

    @NonNull
    @NotNull
    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

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

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles.get(position);
    }
}
  • RecyclerViewAdapter
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> {
    private final Context mContext;

    public RecycleViewAdapter(Context mContext) {
        this.mContext = mContext;
    }

    @NonNull
    @NotNull
    @Override
    public RecycleViewAdapter.ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_card_main, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull RecycleViewAdapter.ViewHolder holder, int position) {
        View view = holder.mView;
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "點(diǎn)擊了", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return 10;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public ViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            mView = itemView;
        }
    }

}

用NavigationView實(shí)現(xiàn)抽屜菜單

design的抽屜菜單和普通側(cè)拉菜單一樣陪每,所有的東西都放在DrawerLayout中影晓,用NavigationView來替代我們此前的自定義控件

  • activity.xml 布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dl_main_drawer"
    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"
    android:fitsSystemWindows="true"
    tools:context=".activity.NetEasyTabActivity">
    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"

        >
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="#ADBE107E"
            app:tabMode="fixed" />


    </com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    />
    </androidx.appcompat.widget.LinearLayoutCompat>
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nv_main_navigation"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/navigation_header"
        app:menu="@menu/drawer_view"/>

</androidx.drawerlayout.widget.DrawerLayout>
  • navigation_header.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="350dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="288dp"
        android:layout_height="272dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/sex" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • drawer_view.xml 菜單文件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <group android:checkableBehavior="single">

        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_launcher"
            android:title="首頁" />

        <item
            android:id="@+id/nav_messages"
            android:icon="@drawable/ic_launcher"
            android:title="事項(xiàng)" />
        <item
            android:id="@+id/nav_friends"
            android:icon="@drawable/ic_launcher"
            android:title="朋友" />
    </group>
    <!--    自動(dòng)分割線-->
    <item android:title="哈哈">
        <menu>
            <group android:checkableBehavior="single">

                <item
                    android:id="@+id/nav_setting"
                    android:icon="@drawable/ic_launcher"
                    android:title="設(shè)置" />
                <item
                    android:id="@+id/nav_other"
                    android:icon="@drawable/ic_launcher"
                    android:title="其他" />
            </group>
        </menu>
    </item>

</menu>
  • java代碼
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_neteasy_tab);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setTitle("虎牙直播");
//        ab.setHomeAsUpIndicator(android.R.drawable.arrow_down_float);
        ab.setHomeButtonEnabled(true);
        ab.setDisplayHomeAsUpEnabled(true);
        nvMainNavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull @NotNull MenuItem item) {
                item.setChecked(true);
                String title = item.getTitle().toString();
                Toast.makeText(NetEasyTabActivity.this, title, Toast.LENGTH_SHORT).show();
                dlMainDrawer.closeDrawers();
                return true;
            }
        });
        initViewPager();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.drawer_view, menu);
        menu.add("測(cè)試動(dòng)態(tài)添加");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_home:
                dlMainDrawer.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

用CoordinatorLayout實(shí)現(xiàn)Toolbar隱藏和折疊

CoordinatorLayout是用來組織其子View之間協(xié)作的一個(gè)父容器View镰吵。默認(rèn)情況下CoordinatorLayout可以理解為一個(gè)FrameLayout,它的布局方式默認(rèn)是一層一層疊上去的挂签。

  • activity布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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:id="@+id/cdl_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".activity.NetEasyTabActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="#ADBE107E"
            app:tabMode="scrollable" />


    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

app:layout_scrollFlags="scroll|enterAlways"這個(gè)屬性設(shè)置滾動(dòng)事件疤祭,屬性里面必須至少啟用scroll這個(gè)flag,這樣這個(gè)view才會(huì)滾出屏幕饵婆,否則將一直固定再頂部

CoordinatorLayout結(jié)合CollapsingToolbarLayout實(shí)現(xiàn)Toolbar折疊效果

CollapsingToolbarLayout的作用是提供一個(gè)可以折疊的Toolbar勺馆。CollapsingToolbarLayout繼承自FrameLayout。它設(shè)置layout_scrollFlag屬性侨核,可以控制包含再CollapsingToolbarLayout中的控件草穆,將布局中的控件包含起來作為一個(gè)可折疊的Toolbar

  • 改造activity布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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:id="@+id/cdl_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".activity.NetEasyTabActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:id="@+id/collapsing_toolbar"
            app:contentScrim="@color/yello"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
           >
            <ImageView
                android:id="@+id/iv_backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:src="@drawable/sex"/>
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
  • app:contentScrim="" 用來設(shè)置CollapsingToolbarLayout收縮后最頂部的顏色
  • app:expandedTitleGravity="left|bottom" 表示將此CollapsingToolbarLayout完全展開后,title所處的位置
  • app:collapsedTitleGravity="left" 表示當(dāng)頭部的視圖消失后title將回歸到Toolbar的位置
  • app:layout_scrillFlags="" 用來設(shè)置滾動(dòng)事件搓译,屬性里面必須至少啟用scroll這個(gè)flag悲柱,這樣這個(gè)view才會(huì)滾動(dòng)出屏幕,否則它將一直固定再頂部些己。

關(guān)于@string/appbar_scrolling_view_behivor 我們需要定義AppBarLayout與滾動(dòng)視圖之間的聯(lián)系豌鸡,Design中包含了一個(gè)特殊的字符串資源@string/appbar_scrolling_view_behivor,它和AppBarLayout.ScrollingViewBehivor相匹配,用來通知AppBarLayout何時(shí)發(fā)生了滾動(dòng)事件段标,這個(gè)Behaivor需要設(shè)置在觸發(fā)事件的View之上涯冠,所以我們需要給RecyclerView設(shè)置

自定義Behvior

CoordinatorLayout中最經(jīng)典的設(shè)計(jì)就是Behavior,我們也可以自定義Behavior來實(shí)現(xiàn)自己的組件和華東交互逼庞。

  1. 定義的View監(jiān)聽CoordinatorLayout里的滑動(dòng)狀態(tài)
  2. 自定義View監(jiān)聽另一個(gè)View的狀態(tài)變化
  • 布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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:id="@+id/cdl_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".activity.NetEasyTabActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:expanded="false">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/yello"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/iv_backdrop"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="fitStart"
                android:src="@drawable/sex" />

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@android:color/holo_blue_dark"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="15dp"
<!--添加自定義behavior-->        app:layout_behavior="com.probuing.androidlight.behavior.FooterBehavior">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="自定義Behavior"
            android:textColor="@color/white" />
    </androidx.appcompat.widget.LinearLayoutCompat>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
  • 自定義behavior
package com.probuing.androidlight.behavior;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewPropertyAnimator;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.ViewCompat;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;

import org.jetbrains.annotations.NotNull;

public class FooterBehavior extends CoordinatorLayout.Behavior<View> {
    //滑動(dòng)距離累加值
    private int directionChange;
    public FooterBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    public boolean onStartNestedScroll(@NonNull @NotNull CoordinatorLayout coordinatorLayout, @NonNull @NotNull View child, @NonNull @NotNull View directTargetChild, @NonNull @NotNull View target, int axes) {
        return (axes & ViewCompat.SCROLL_AXIS_VERTICAL)!=0;
    }

    @Override
    public void onNestedPreScroll(@NonNull @NotNull CoordinatorLayout coordinatorLayout,
                                  @NonNull @NotNull View child, @NonNull @NotNull View target,
                                  int dx,
                                  int dy,
                                  @NonNull @NotNull int[] consumed,
                                  int type) {
        if (dy>0&&directionChange<0||dy<0&&directionChange>0) {
            child.animate().cancel();
            directionChange=0;
        }
        directionChange+=dy;
        if (directionChange>child.getHeight()&&child.getVisibility()== View.VISIBLE) {
            hide(child);
        }else if(directionChange<0&&child.getVisibility()==View.GONE){
            show(child);
        }
    }

    private void hide(View view) {
        //設(shè)置動(dòng)畫
        ViewPropertyAnimator animator = view.animate().translationY(view.getHeight())
                .setInterpolator(new FastOutSlowInInterpolator())
                .setDuration(200);
        animator.setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.GONE);

            }
        } );
        animator.start();
    }

    private void show(View view) {
        //設(shè)置動(dòng)畫
        ViewPropertyAnimator animator = view.animate().translationY(0)
                .setInterpolator(new FastOutSlowInInterpolator())
                .setDuration(200);
        animator.setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.VISIBLE);

            }
        } );
        animator.start();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蛇更,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子往堡,更是在濱河造成了極大的恐慌械荷,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件虑灰,死亡現(xiàn)場(chǎng)離奇詭異吨瞎,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)穆咐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門颤诀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人对湃,你說我怎么就攤上這事崖叫。” “怎么了拍柒?”我有些...
    開封第一講書人閱讀 162,764評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵心傀,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我拆讯,道長(zhǎng)脂男,這世上最難降的妖魔是什么养叛? 我笑而不...
    開封第一講書人閱讀 58,193評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮宰翅,結(jié)果婚禮上弃甥,老公的妹妹穿的比我還像新娘。我一直安慰自己汁讼,他們只是感情好淆攻,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,216評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著嘿架,像睡著了一般瓶珊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上眶明,一...
    開封第一講書人閱讀 51,182評(píng)論 1 299
  • 那天艰毒,我揣著相機(jī)與錄音筐高,去河邊找鬼搜囱。 笑死,一個(gè)胖子當(dāng)著我的面吹牛柑土,可吹牛的內(nèi)容都是我干的蜀肘。 我是一名探鬼主播,決...
    沈念sama閱讀 40,063評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼稽屏,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼扮宠!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起狐榔,我...
    開封第一講書人閱讀 38,917評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤坛增,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后薄腻,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體收捣,經(jīng)...
    沈念sama閱讀 45,329評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,543評(píng)論 2 332
  • 正文 我和宋清朗相戀三年庵楷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了罢艾。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,722評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡尽纽,死狀恐怖咐蚯,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情弄贿,我是刑警寧澤春锋,帶...
    沈念sama閱讀 35,425評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站差凹,受9級(jí)特大地震影響期奔,放射性物質(zhì)發(fā)生泄漏豆拨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,019評(píng)論 3 326
  • 文/蒙蒙 一能庆、第九天 我趴在偏房一處隱蔽的房頂上張望施禾。 院中可真熱鬧,春花似錦搁胆、人聲如沸弥搞。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽攀例。三九已至,卻和暖如春顾腊,著一層夾襖步出監(jiān)牢的瞬間粤铭,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工杂靶, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留梆惯,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,729評(píng)論 2 368
  • 正文 我出身青樓吗垮,卻偏偏與公主長(zhǎng)得像垛吗,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子烁登,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,614評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容