Android之AppBarLayout實現懸停吸附伸縮效果

weixin_34402408發表於2018-09-28

前幾天看到這樣一個UI效果,然後自己也仿照實現了下:

5549640-9e3cecfad8df9334.gif
開眼app個人中心.gif

看著挺酷的,也有很多App都用到了這個UI效果,比如開眼App和滬江開心詞場就用到了.
所以下面就來簡單實現一下這個UI效果吧.

組合三劍客

1.AppBarLayout
2.CoordinatorLayout
3.CollapsingToolbarLayout

實現上面的UI效果需要將這三劍客的組合起來用,下面先介紹下這三個控制元件:

AppBarLayout:

1.AppBarLayout簡單介紹

AppBarLayout是android.support:design包中的支援的控制元件,繼承自LinearLayout,實際上就是一個垂直分佈的LinearLayout.父類檢視結構如下:

public class AppBarLayout 
extends LinearLayout

java.lang.Object 
   ↳  android.view.View
      ↳ android.view.ViewGroup
           ↳  android.widget.LinearLayout  
              ↳ android.support.design.widget.AppBarLayout 

其中官方文件中有這麼兩句話尤為重要:

This view depends heavily on being used as a direct child within a CoordinatorLayout. If you use AppBarLayout within a different ViewGroup, most of it's functionality will not work.

AppBarLayout also requires a separate scrolling sibling in order to know when to scroll. The binding is done through the AppBarLayout.ScrollingViewBehavior behavior class, meaning that you should set your scrolling view's behavior to be an instance of AppBarLayout.ScrollingViewBehavior.

意思就是說AppBarLayout 必須作為CoordinatorLayout的直接子類,否則很多功能是無法實現的.並且AppBarLayout 必須有一個能滾動的兄第ScrollView (實現了NestedScrollView,listview不可以哦),以此來通知AppBarLayout 何時進行滾動,兄弟View必須實現以下標識:

app:layout_behavior="@string/appbar_scrolling_view_behavior"

官方給出的例子如下:

<android.support.design.widget.CoordinatorLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

     <android.support.v4.widget.NestedScrollView
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             app:layout_behavior="@string/appbar_scrolling_view_behavior">

         <!-- Your scrolling content -->

     </android.support.v4.widget.NestedScrollView>

     <android.support.design.widget.AppBarLayout
             android:layout_height="wrap_content"
             android:layout_width="match_parent">

         <android.support.v7.widget.Toolbar
                 ...
                 app:layout_scrollFlags="scroll|enterAlways"/>

         <android.support.design.widget.TabLayout
                 ...
                 app:layout_scrollFlags="scroll|enterAlways"/>

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

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

2.AppBarLayout的具體使用

  • AppBarLayout直接子View的幾種響應方式

AppbarLayout 可以指定當某個可滑動的兄弟View滑動手勢改變時AppbarLayout 內部直接子View的響應動作,只要通過app:layout_scrollFlags屬性來指定響應動作,layout_scrollFlags有5種響應動作,下面簡單介紹下:

  1. app:layout_scrollFlags="scroll"
    當子view設定響應動作為app:layout_scrollFlags="scroll"時,子view會隨ScrollView 的滾動而滾動,就相當於這時的子view變成了ScrollView 的item了,會跟隨item一起滾動.
<android.support.v7.widget.Toolbar
                   android:layout_width="match_parent"
                   android:layout_height="?attr/actionBarSize"
                   app:title="AppbarLayout"
                   app:titleTextColor="@color/white"
                   app:layout_scrollFlags="scroll"
                   >

               </android.support.v7.widget.Toolbar>
  1. app:layout_scrollFlags="scroll|enterAlways"
    當子view設定響應動作為app:layout_scrollFlags="scroll|enterAlways"時,當ScrollView 向下滑動時,子View 將直接向下滑動,而不管ScrollView 是否在滑動。
<android.support.v7.widget.Toolbar
                   android:layout_width="match_parent"
                   android:layout_height="?attr/actionBarSize"
                   app:title="AppbarLayout"
                   app:titleTextColor="@color/white"
                   app:layout_scrollFlags="scroll|enterAlways"
                   />

3.app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
當子view設定響應動作為app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"時,
當ScrollView 向下滑動的時候,子View(設定了enterAlwaysCollapsed 的子View)下滑至摺疊的高度,當ScrollView 到達滑動範圍的結束值的時候,滑動View剩下的部分開始滑動。這個摺疊的高度是通過子View的minimum height (最小高度)指定的。

簡單來說,就是第二種的加強版,當ScrollView 向下滑動時候,子view先露出半個頭,當ScrollView 下滑到頂時,子view的頭就全露出來了.

<android.support.v7.widget.Toolbar
                   android:layout_width="match_parent"
                   android:layout_height="200dp"
                   android:minHeight="?attr/actionBarSize"
                   app:title="AppbarLayout"
                   android:gravity="bottom"
                   android:layout_marginBottom="25dp"
                   app:titleTextColor="@color/white"
                   app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
                   />

4.app:layout_scrollFlags="scroll|exitUntilCollapsed"
當子view設定響應動作為app:layout_scrollFlags="scroll|exitUntilCollapsed"時,
當ScrollView 向上滑動時,子View先響應滑動事件,滑動至摺疊高度,也就是通過minimum height 設定的最小高度後,就固定不動了,再把滑動事件交給 scrollview,然後 scrollview才開始滑動。

<android.support.v7.widget.Toolbar
                   android:layout_width="match_parent"
                   android:layout_height="200dp"
                   android:minHeight="?attr/actionBarSize"
                   app:title="AppbarLayout"
                   android:gravity="bottom"
                   app:titleTextColor="@color/white"
                   app:layout_scrollFlags="scroll|exitUntilCollapsed"
                   />
  1. app:layout_scrollFlags="scroll|snap"
    當子view設定響應動作為app:layout_scrollFlags="scroll|snap"時,當ScrollView 下滑到頂部時,如果子view只露出30%的話,子view就會自動摺疊回去,如果露出60%的話,就會自動展開.

簡單來說,就是具有彈性且遵守就近原則,露的小就乾脆不露頭了,露的大,就全部出來了.

<android.support.v7.widget.Toolbar
                   android:layout_width="match_parent"
                   android:layout_height="200dp"
                   android:minHeight="?attr/actionBarSize"
                   app:title="AppbarLayout"
                   android:gravity="bottom"
                   app:titleTextColor="@color/white"
                   app:layout_scrollFlags="scroll|snap"
                   />

CoordinatorLayout

CoordinatorLayout 用來調節和控制子View的滾動,而這些子View 的具體響應動作是通過 behavior 屬性來指定的,你也可以根據需求自定義自己的behavior, 簡單使用如下:,

<android.support.design.widget.CoordinatorLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

     <android.support.v4.widget.NestedScrollView
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             app:layout_behavior="@string/appbar_scrolling_view_behavior" >
 <!-- 使用此屬性指定響應 -->

         <!-- Your scrolling content -->

     </android.support.v4.widget.NestedScrollView>

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

    app:layout_behavior="@string/appbar_scrolling_view_behavior" >
 <!-- 使用此屬性指定響應 -->

CollapsingToolbarLayout:

CollapsingToolbarLayout也是android.support:design包中的支援的控制元件,繼承自FrameLayout.主要用於實現ToolBar的伸縮效果,而且必須為AppBarLayout的直接子View;

繼承結構圖如下:

 java.lang.Object 
   ↳ android.view.View  
     ↳ android.view.ViewGroup  
        ↳ android.widget.FrameLayout   
           ↳  android.support.design.widget.CollapsingToolbarLayout 

主要使用到的方法如下:

  1. setCollapsedTitleGravity
void setCollapsedTitleGravity(int gravity)

設定摺疊標題和垂直重力的水平對齊方式,當摺疊邊界中有額外空間超出標題本身所需的空間時,將使用該對齊方式
相關的XML屬性:

CollapsingToolbarLayout_collapsedTitleGravity

2.setExpandedTitleGravity

void setExpandedTitleGravity(int gravity)

設定展開標題和垂直重力的水平對齊方式,當擴充套件邊界中有額外空間超出標題本身所需的空間時,將使用該對齊方式。
相關的XML屬性:

CollapsingToolbarLayout_expandedTitleGravity

3.setExpandedTitleTextColor

void setExpandedTitleTextColor(ColorStateList colors)

設定展開標題的文字顏色。

4.setCollapsedTitleTextColor

void setCollapsedTitleTextColor(ColorStateList colors)

設定摺疊標題的文字顏色。

5.setCollapsedTitleTypeface

void setCollapsedTitleTypeface(字型字型)

設定用於摺疊標題的字型。

5.setExpandedTitleMarginBottom

void setExpandedTitleMarginBottom(int margin)

以畫素為單位設定底部展開的標題邊距。
相關的XML屬性:

CollapsingToolbarLayout_expandedTitleMarginBottom
  1. 固定Toolbar
app:layout_collapseMode="pin"

6.更多方法見文件

關於AppBarLayout的三劍客組合就介紹的差不多了,想進一步瞭解的可以去查閱官方文件,上面都給出了連線的.

特別說明:

三劍客配合使用,可以做出一些很炫酷的UI效果.
但是前提必須滿足:AppbarLayout 要作為CoordinatorLayout 的直接子View,而CollapsingToolbarLayout 要作為AppbarLayout 的直接子View ,否則,上面展示的效果將實現不了.

AppbarLayout例項展示

1.仿 [開眼App]個人中心效果

  • .xml佈局檔案:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    xmlns:imagetext="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:background="@color/colorWhite"

    >

<android.support.design.widget.AppBarLayout
    android:id="@+id/center_appbar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp"
    android:background="@color/colorWhite"
    android:fitsSystemWindows="true"

    >

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toobar"
        android:layout_width="match_parent"
        android:layout_height="260dp"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:contentScrim="@color/colorGraylight"
        fresco:expandedTitleTextAppearance="@style/style_textsize1"
        fresco:collapsedTitleTextAppearance="@style/style_textsize"
        fresco:collapsedTitleGravity="left"
       fresco:expandedTitleMarginTop="185dp"
        fresco:expandedTitleGravity="left"
        fresco:expandedTitleMarginStart="30dp"
        >
        <FrameLayout
            app:layout_scrollFlags="scroll"
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <com.facebook.drawee.view.SimpleDraweeView
                android:id="@+id/avatar_max"
                android:layout_width="match_parent"
                android:layout_height="170dp" />


            <com.facebook.drawee.view.SimpleDraweeView
                android:layout_marginLeft="20dp"
                android:layout_gravity="bottom"
                android:id="@+id/avatar_min"
                android:layout_width="70dp"
                android:layout_height="70dp"
                fresco:actualImageScaleType="centerCrop"
                fresco:placeholderImageScaleType="centerCrop"
                fresco:roundedCornerRadius="50dp"
                />
        </FrameLayout>

        <FrameLayout
            android:layout_marginTop="180dp"
            app:layout_scrollFlags="scroll"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            >

            <Button
                android:id="@+id/edit_btn"
                android:layout_width="60dp"
                android:layout_height="20dp"
                android:layout_marginRight="20dp"
                android:layout_gravity="right|center_vertical"
                android:background="@drawable/login_btn"
                android:gravity="center"
                android:text="編輯資料"
                android:textColor="@color/colorBlacklight"
                android:textSize="10sp" />
        </FrameLayout>

        <TextView
           android:layout_marginTop="230dp"
            app:layout_scrollFlags="scroll"
            android:textSize="10sp"
            android:id="@+id/date"
            android:layout_marginLeft="20dp"
            android:text="2018.07.08註冊"
            android:textColor="@color/colorGraylight"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            app:layout_collapseMode="pin"
            android:layout_height="?attr/actionBarSize"
            >
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>







    <LinearLayout
        android:gravity="center_vertical"
        android:layout_marginTop="20dp"
        android:background="@color/colorGrayalpha"
        android:layout_width="match_parent"
        android:layout_height="70dp">

        <openeyes.dr.openeyes.widget.CustomImageTextView
            android:id="@+id/works"
            android:layout_marginLeft="40dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            imagetext:image="@drawable/works2"
            imagetext:text="@string/works"
            imagetext:textColor="@color/colorGraylight"
            >
        </openeyes.dr.openeyes.widget.CustomImageTextView>

        <openeyes.dr.openeyes.widget.CustomImageTextView
            android:id="@+id/attention"
            android:layout_marginLeft="90dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            imagetext:image="@drawable/attention6"
            imagetext:text="@string/attention"
            imagetext:textColor="@color/colorGraylight"
            >
        </openeyes.dr.openeyes.widget.CustomImageTextView>
        <openeyes.dr.openeyes.widget.CustomImageTextView
            android:id="@+id/fans"
            android:layout_marginLeft="90dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            imagetext:image="@drawable/works2"
            imagetext:text="@string/fans"
            imagetext:textColor="@color/colorGraylight"
            >
        </openeyes.dr.openeyes.widget.CustomImageTextView>
    </LinearLayout>

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle_state"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        />




</android.support.design.widget.CoordinatorLayout>
  • java檔案:
/**
 * Created by darryrzhong on 2018/9/5.
 */

public class PersonPageActivity extends SwipeBackActivity {

    @BindView(R.id.avatar_max)
    SimpleDraweeView avatarBackground;
    @BindView(R.id.avatar_min)
    SimpleDraweeView avatarUser;
    @BindView(R.id.date)
    TextView registerDate;
    @BindView(R.id.works)
    CustomImageTextView works;
    @BindView(R.id.attention)
    CustomImageTextView attention;
    @BindView(R.id.fans)
    CustomImageTextView fans;
    @BindView(R.id.center_appbar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.collapsing_toobar)
    CollapsingToolbarLayout collToobar;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.recycle_state)
    RecyclerView recyclerView;
    private SharedPreferences sharedPreferences = MyApplication.sharedPreferences;
    private HistoryDB db;
    private List<HistoryDetails> details  = null;
    private DynamicStateRecyclerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_page);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initData() {
        db = new HistoryDB();
        details= db.loadHistoryByUserId(sharedPreferences.getString("userId","000"));
        if (details==null||details.size()==0){

        }else {
            Collections.reverse(details);
            adapter = new DynamicStateRecyclerAdapter(details,this);
            LinearLayoutManager manager = new LinearLayoutManager(this);
            manager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(manager);
            recyclerView.setAdapter(adapter);
            recyclerView.setItemAnimator(new DefaultItemAnimator());//新增預設動畫
            //設定RecyclerView的item監聽事件
            setOnItemClickListener();
        }


    }

    private void setOnItemClickListener() {

        adapter.setOnItemClickListener(new DynamicStateRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemview, DynamicStateRecyclerAdapter.MyViewHolder childview, int position) {
                initVideoDetail( position);//初始化視訊詳情介面資料並實現跳轉
            }
        });
    }

    /**
     * 初始化視訊詳情介面資料,跳轉至視訊詳情介面
     * */
    private void initVideoDetail(int position) {
        Intent intent = new Intent(PersonPageActivity.this, VideoDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("title",details.get(position).getTitle());//獲取標題
        bundle.putString("time", details.get(position).getDetail());
        bundle.putString("desc", details.get(position).getDesc());//視訊描述
        bundle.putString("blurred", details.get(position).getBlurred());//模糊圖片地址
        bundle.putString("feed", details.get(position).getPhoto());//圖片地址
        bundle.putString("video", details.get(position).getVideo());//視訊播放地址
        bundle.putInt("collect", details.get(position).getCollect());//收藏量
        bundle.putInt("share", details.get(position).getShare());//分享量
        bundle.putInt("reply", details.get(position).getReply());//回覆數量
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void initView() {
        avatarBackground.setImageURI(Uri.parse(sharedPreferences.getString("userIcon","")));
        avatarUser.setImageURI(Uri.parse(sharedPreferences.getString("userIcon","")));
        toolbar.setTitle(sharedPreferences.getString("userName",""));//設定標題
        collToobar.setExpandedTitleColor(getResources().getColor(R.color.colorBlack));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationIcon(R.drawable.back_black);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @OnClick(R.id.attention)
    public void onClick(){
        startActivity(new Intent(this,MyAttentionActivity.class));
    }


}

效果展示:

5549640-7e47a81560bdce78.gif
開眼app個人中心.gif

2.仿[開眼App]搜尋懸停介面:

  • .xml佈局檔案:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <openeyes.dr.openeyes.widget.SearchEditText
            android:id="@+id/search_editext"
            android:layout_marginLeft="20dp"
            android:background="@drawable/shape_search"
            android:layout_width="300dp"
            android:layout_height="30dp"
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            android:gravity="start|center_vertical"
            android:imeOptions="actionSearch"
            android:singleLine="true"
            android:hint="搜尋視訊、作者、使用者及標籤"
            android:textSize="13sp"

            />

        <TextView
            android:id="@+id/cancle_main"
            android:textColor="@color/colorBlacklight"
            android:gravity="center"
            android:text="取消"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <FrameLayout
        android:id="@+id/history_fl"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        >

        <TextView
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="20dp"
            android:textSize="20sp"
            android:text="搜尋歷史"
            android:textColor="@color/colorBlack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/delete_history"
            android:layout_marginRight="20dp"
            android:layout_gravity="center_vertical|right"
            android:textColor="@color/colorAniBtns"
            android:gravity="center"
            android:text="清空"
            android:textSize="13sp"
            android:layout_width="50dp"
            android:layout_height="wrap_content" />
    </FrameLayout>

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@color/colorWhite"
        >


        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorWhite"

            >
            <android.support.v7.widget.RecyclerView
                android:id="@+id/search_history_rv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll"
                >

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


            <TextView
                android:layout_marginLeft="20dp"
                android:text="熱搜關鍵詞"
                android:textSize="20sp"
                android:textColor="@color/colorBlack"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

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



        <android.support.v7.widget.RecyclerView
            android:id="@+id/hot_search_rv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            >

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

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


</LinearLayout>
  • java檔案:
package openeyes.dr.openeyes.view.activity;

/**
 * Created by darryrzhong on 2018/9/10.
 */

public class SearchActivity extends AppCompatActivity {

    @BindView(R.id.search_editext)
    SearchEditText searchEditText;
    @BindView(R.id.cancle_main)
    TextView cancleMain;
    @BindView(R.id.history_fl)
    FrameLayout hintLayout;
    @BindView(R.id.delete_history)
    TextView deleteHistory;
    @BindView(R.id.search_history_rv)
    RecyclerView recyclerSearch;
    @BindView(R.id.hot_search_rv)
    RecyclerView recyclerHot;
    private String [] hotKeyWord = {"美食","旅行","生活小技巧","健身","汽車","廣告","動畫",
            "創意靈感","當下亂碼","一條","日食記","視知TV"};
    private List<SearchHistory> searchHistories;
    private List<SearchHistory> hotKeyWords = new ArrayList<>();;
    private SearchRecyclerAdapter adapter;
    private SearchDB db;
    private SearchRecyclerAdapter adapter1;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        initData();
        setListener();
    }

    private void initData() {
        db = new SearchDB();
        hotKeyWords.clear();
        for (String keyWord:hotKeyWord){
            hotKeyWords.add(new SearchHistory(keyWord));
        }

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayout.VERTICAL);
        recyclerHot.setLayoutManager(manager);
        adapter = new SearchRecyclerAdapter(hotKeyWords);
        recyclerHot.setAdapter(adapter);
        recyclerHot.setItemAnimator(new DefaultItemAnimator());

        searchHistories = db.loadSearchHistoryAll();
        if (searchHistories==null||searchHistories.size()==0){
            hintLayout.setVisibility(View.GONE);
            recyclerSearch.setVisibility(View.GONE);
        }else {
            hintLayout.setVisibility(View.VISIBLE);
            Collections.reverse(searchHistories);
            LinearLayoutManager manager1 = new LinearLayoutManager(this);
            manager.setOrientation(LinearLayout.VERTICAL);
            recyclerSearch.setLayoutManager(manager1);
            adapter1 = new SearchRecyclerAdapter(searchHistories);
            recyclerSearch.setAdapter(adapter1);
            recyclerSearch.setItemAnimator(new DefaultItemAnimator());//新增預設動畫
            adapter1.setOnItemClickListener(new SearchRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View itemview, SearchRecyclerAdapter.MyViewHolder childview, int position) {
                    Intent intent = new Intent(SearchActivity.this,SearchResultActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("keyWord",searchHistories.get(position).getKeyWord());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
        }

    }

    private void setListener() {
        searchEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyCode==KeyEvent.KEYCODE_ENTER&&keyEvent.getAction()==KeyEvent.ACTION_DOWN){
                       String keyWord = searchEditText.getText().toString().trim();
                       if ("".equals(keyWord)){
                           ToastUtil.showToast(SearchActivity.this,"請輸入搜尋內容");
                       }else {
                           SearchHistory searchHistory = new SearchHistory(keyWord);
                           List<SearchHistory> temp = db.loadSearchByKeyWord(keyWord);
                           if (temp==null){
                               db.saveOrUpdate(searchHistory);
                           }else if (temp.size()==0){
                               db.saveOrUpdate(searchHistory);
                           }
                           Intent intent = new Intent(SearchActivity.this,SearchResultActivity.class);
                           Bundle bundle = new Bundle();
                           bundle.putString("keyWord",keyWord);
                           intent.putExtras(bundle);
                           startActivity(intent);
                       }
                }
                return false;
            }
        });

        adapter.setOnItemClickListener(new SearchRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemview, SearchRecyclerAdapter.MyViewHolder childview, int position) {
                Intent intent = new Intent(SearchActivity.this,SearchResultActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("keyWord",hotKeyWords.get(position).getKeyWord());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });


    }

    @OnClick({R.id.cancle_main,R.id.delete_history,R.id.search_editext})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.cancle_main:
                finish();
                break;
            case R.id.delete_history:
                try {
                    db.delTable();
                } catch (DbException e) {
                    e.printStackTrace();
                }
                initData();

                break;
            case R.id.search_editext:
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }
}

效果展示:

5549640-1e6bdf17608d33ae.gif
開眼app搜尋記錄.gif

好了,到這裡關於AppBarLayout三劍客的基本使用就介紹完了,使用三劍客能夠實現許多炫酷的UI效果,感興趣的朋友可以自行自定義.

歡迎關注作者darryrzhong,更多幹貨等你來拿喲.

請賞個小紅心!因為你的鼓勵是我寫作的最大動力!

更多精彩文章請關注

相關文章