PopupWindow的简单使⽤(结合RecyclerView)Android弹窗:
在Android中弹出式菜单(以下称弹窗)是使⽤⼗分⼴泛⼀种菜单呈现的⽅式,弹窗为⽤户交互提供了便利。关于弹窗的实现⼤致有以下两种⽅式AlertDialog和PopupWindow;
两者的区别:AlertDialog弹窗在位置显⽰上是固定的,⽽PopupWindow则相对⽐较随意,能够在主屏幕上的任意位置显⽰;
今天就简单介绍⼀下,如何利⽤PopupWindow实现RecyclerView的⾃定义的弹窗布局;
使⽤步骤:
1.创建两个xml⽂件,⼀个mainactivity主布局,⼀个是popupwindow布局(因为我是在项⽬⾥写的,所以闲杂代码可能⽐较多):
主布局(在其写⼀个Button按钮,因为项⽬需要,我换成了ImageView):
alertdialog使用方法<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>
<LinearLayout xmlns:android="schemas.android/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="schemas.android/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();
}
});
showPopupWindow()⽅法:
1.先将l布局加载成⼀个View,并通过该View将RecyclerView进⾏实例化,然后RecyclerView进⾏设置,在这设置成竖向排列的线性布局,然后为其设置⼀个Adapter;
2.随后将popupWindow进⾏设置:
main_layout是ImageView的⽗容器LinearLayout,
第⼀个ViewGroup.LayoutParams.WRAP_CONTENT是设置popupwindow的宽度,第⼆个
ViewGroup.LayoutParams.WRAP_CONTENT是设置popupwindow的⾼度;
设置popupwindow的布局;
调⽤PopupWindow的showAsDropDown(View view)将PopupWindow作为View组件的下拉组件显⽰出来;或调⽤PopupWindow的showAtLocation()⽅法将PopupWindow在指定位置显⽰出来;
最后的效果如图: 想了解更多PopupWindow的⽤法,请看下⾯的简书: 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); }
popupWindow = new PopupWindow(main_layout, ViewGroup .LayoutParams.WRAP _CONTENT, ViewGroup .LayoutParams.WRAP _CONTENT);popupWindow .setContentView (view);
popupWindow .showAsDropDown (bselect);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论