Android彈窗:
在Android中彈出式菜單(以下稱彈窗)是使用十分廣泛一種菜單呈現的方式,彈窗為用戶交互提供了便利。關於彈窗的實現大致有以下兩種方式AlertDialog和PopupWindow;
兩者的區別:AlertDialog彈窗在位置顯示上是固定的,而PopupWindow則相對比較隨意,能夠在主屏幕上的任意位置顯示;
今天就簡單介紹一下,如何利用PopupWindow實現RecyclerView的自定義的彈窗布局;
使用步驟:
1.創建兩個xml文件,一個mainactivity主布局,一個是popupwindow布局(因為我是在項目里寫的,所以閑雜代碼可能比較多):
主布局(在其寫一個Button按鈕,因為項目需要,我換成了ImageView):
<LinearLayout android:id="@+id/score_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior" android:background="#f0f0f0"> <ImageView android:id="@+id/bttest" android:layout_width="50dp" android:layout_height="match_parent" android:layout_gravity="center" android:src="@mipmap/selectteam" /> </LinearLayout>
popupwindow.xml布局(里面放一個RecyclerView):
<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"> <android.support.v7.widget.RecyclerView android:id="@+id/select" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_scrollFlags="scroll|enterAlways|snap"> </android.support.v7.widget.RecyclerView> </LinearLayout>
2.在MainActivity中為ImageView進行實例化,並為其設立點擊事件:
bselect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPopupWindow(); } });
private void showPopupWindow() {
View view = LayoutInflater.from(getContext()).inflate(R.layout.popupwindow,null); RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.select); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(linearLayoutManager); ScoreTeamAdapter scoreTeamAdapter = new ScoreTeamAdapter(yearList); recyclerView.setAdapter(scoreTeamAdapter); popupWindow = new PopupWindow(main_layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setContentView(view); popupWindow.setFocusable(true); popupWindow.showAsDropDown(bselect); }
showPopupWindow()方法:
1.先將popupwindow.xml布局加載成一個View,並通過該View將RecyclerView進行實例化,然后RecyclerView進行設置,在這設置成豎向排列的線性布局,然后為其設置一個Adapter;
2.隨后將popupWindow進行設置:
popupWindow = new PopupWindow(main_layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
main_layout是ImageView的父容器LinearLayout,
第一個ViewGroup.LayoutParams.WRAP_CONTENT是設置popupwindow的寬度,第二個ViewGroup.LayoutParams.WRAP_CONTENT是設置popupwindow的高度;
popupWindow.setContentView(view);
設置popupwindow的布局;
popupWindow.showAsDropDown(bselect);
調用PopupWindow的showAsDropDown(View view)將PopupWindow作為View組件的下拉組件顯示出來;或調用PopupWindow的showAtLocation()方法將PopupWindow在指定位置顯示出來;
最后的效果如圖: 
想了解更多PopupWindow的用法,請看下面的簡書:
http://www.jianshu.com/p/825d1cc9fa79
