弹窗库XPopup组件怎么用

免费建站   2024年03月29日 23:42  

本篇文章为大家展示了弹窗库XPopup组件怎么用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

1. 介绍

XPopup是一个弹窗库,可能是Harmony平台最好的弹窗库。它从设计的时候就本着实用的原则,兼顾了美观和优雅的交互。用户都喜欢自然舒适的UI和交互,希望XPopup能带给你一些帮助或者惊喜!

2.依赖allprojects{repositories{mavenCentral()}}implementation'io.openharmony.tpc.thirdlib::1.0.3'3. 如何使用3.1 内置弹窗的使用3.1.1 显示确认和取消对话框newXPopup.Builder(getContext()).asConfirm("我是","我是内容",newOnConfirmListener(){@OverridepublicvoidonConfirm(){toast("clickconfirm");}}).show();3.1.2 显示待输入框的确认和取消对话框newXPopup.Builder(getContext()).asInputConfirm("我是","请输入内容。",newOnInputConfirmListener(){@OverridepublicvoidonConfirm(Stringtext){toast("inputtext:"+text);}}).show();3.1.3 显示中间弹出的列表弹窗newXPopup.Builder(getContext())//.maxWidth(600).asCenterList("请选择一项",newString[]{"条目1","条目2","条目3","条目4"},newOnSelectListener(){@OverridepublicvoidonSelect(intposition,Stringtext){toast("click"+text);}}).show();3.1.4 显示中间弹出的加载框newXPopup.Builder(getContext()).asLoading("正在加载中").show();3.1.5 显示从底部弹出的列表弹窗newXPopup.Builder(getContext()).asBottomList("请选择一项",newString[]{"条目1","条目2","条目3","条目4","条目5"},newOnSelectListener(){@OverridepublicvoidonSelect(intposition,Stringtext){toast("click"+text);}}).show();3.1.6 显示依附于某个Component或者某个点的弹窗newXPopup.Builder(getContext()).atView(component)//依附于所点击的Component,内部会自动判断在上方或者下方显示.asAttachList(newString[]{"分享","编辑","不带icon"},newint[]{ResourceTable.Media_icon,ResourceTable.Media_icon},newOnSelectListener(){@OverridepublicvoidonSelect(intposition,Stringtext){toast("click"+text);}}).show();

如果是想依附于某个Component的触摸点,则需要先watch该Component,然后当单击或长按触发的时候去显示:

Componentcomponent=findComponentById(ResourceTable.Id_btnShowAttachPoint);//必须在事件发生前,调用这个方法来监视View的触摸finalXPopup.Builderbuilder=newXPopup.Builder(getContext()).watchView(component);component.setLongClickedListener(newLongClickedListener(){@OverridepublicvoidonLongClicked(Componentcomponent){builder.asAttachList(newString[]{"置顶","复制","删除"},null,newOnSelectListener(){@OverridepublicvoidonSelect(intposition,Stringtext){toast("click"+text);}}).show();}});

asAttachList方法内部是对AttachPopupView的封装,如果你的布局不是列表,可以继承AttachPopupView实现自己想要的布局。AttachPopupView会出现在目标的上方或者下方,如果你想要出现在目标的左边或者右边(像微信朋友圈那样点赞的弹窗),可以继承HorizontalAttachPopupView,然后编写你的布局即可。

最简单的示例如下:

publicclassCustomAttachPopupextendsHorizontalAttachPopupView{publicCustomAttachPopup(Contextcontext){super(context,null);}@OverrideprotectedintgetImplLayoutId(){returnResourceTable.Layout_custom_attach_popup;}@OverrideprotectedvoidonCreate(){super.onCreate();findComponentById(ResourceTable.Id_tv_zan).setClickedListener(newClickedListener(){@OverridepublicvoidonClick(Componentcomponent){ToastUtil.showToast(getContext(),"赞");dismiss();}});findComponentById(ResourceTable.Id_tv_comment).setClickedListener(newClickedListener(){@OverridepublicvoidonClick(Componentcomponent){ToastUtil.showToast(getContext(),"评论");dismiss();}});}//设置状态栏的高度,用以修正自定义位置弹窗的高度@OverrideprotectedintsetStatusBarHeight(){return130;}}3.1.7 显示大图浏览弹窗//当你点击图片的时候执行以下代码://多图片场景(你有多张图片需要浏览)newXPopup.Builder(getContext()).asImageViewer(image,position,list,newOnSrcViewUpdateListener(){@OverridepublicvoidonSrcViewUpdate(ImageViewerPopupViewpopupView,intposition){//pager更新当前显示的图片//当启用isInfinite时,position会无限增大,需要映射为当前ViewPager中的页intrealPosi=position%list.size();pager.setCurrentPage(realPosi,false);}},newImageLoader()).show();//单张图片场景newXPopup.Builder(getContext()).asImageViewer(image,url,newImageLoader()).show();//图片加载器,XPopup不负责加载图片,需要你实现一个图片加载器传给我,这里以Glide和OkGo为例(可直接复制到项目中):classImageLoaderimplementsXPopupImageLoader{@OverridepublicvoidloadImage(intposition,Stringurl,ImageimageView){//一进入页面就加载图片的话,需要加点延迟context.getUITaskDispatcher().delayDispatch(newRunnable(){@Overridepublicvoidrun(){Glide.with(context).load(url).diskCacheStrategy(DiskCacheStrategy.ALL).into(image);}},50);}//必须实现这个方法,用来下载图片。可参照下面的实现,内部保存图片会用到。如果你不需要保存图片这个功能,可以返回null。@OverridepublicFilegetImageFile(Contextcontext,Stringurl){try{returnOkGo.<File>get(url).tag(this).converter(newFileConvert()).adapt().execute().body();}catch(Exceptione){LogUtil.error(TAG,e.getMessage());}returnnull;}}

如果你用的不是Glide,请参考去实现即可。

3.1.8 关闭弹窗

先拿到弹窗对象,以Loading弹窗为例,其他也是一样:

BasePopupViewpopupView=newXPopup.Builder(getContext()).asLoading("正在加载中").show();

执行消失:

//有四个消失方法可供选择:popupView.dismiss();//立即消失popupView.delayDismiss(300);//延时消失,有时候消失过快体验可能不好,可以延时一下popupView.smartDismiss();//会等待弹窗的开始动画执行完毕再进行消失,可以防止接口调用过快导致的动画不完整。popupView.dismissWith({});//消失动画执行完之后执行某些逻辑

我们在项目中经常会点击某个按钮然后关闭弹窗,接着去做一些事。比如:点击一个按钮,关闭弹窗,然后开启一个界面,要知道弹窗的关闭是有一个动画过程的,上面的写法会出现弹窗还没有完全关闭,就立即跳页面,界面有一种顿挫感;而且在设备资源不足的时候,还可能造成丢帧。所以很多时候不推荐直接使用dismiss()方法,除非你关闭完弹窗后面没有任何逻辑执行。

为了得到最佳体验,您可以等dismiss动画完全结束去执行一些东西,而不是立即就执行。可以这样做:

popupView.dismissWith(newRunnable(){@Overridepublicvoidrun(){//跳转到新页面}});

每个弹窗本身也有onShow()和onDismiss()的生命周期回调,可以根据需要使用。

还有这样一种场景:弹窗show()完之后,你的逻辑执行完毕,然后调用dismiss()。但是你的逻辑执行过快,可能导致弹窗的show动画还没有执行完就直接dismiss了,界面上的感觉并不好。这个时候推荐使用smartDismiss()方法,这个方法能保证弹窗的show动画执行完再关闭弹窗。

3.1.9 复用项目已有布局

如果你项目中已经有写好的弹窗布局,而想用XPopup提供的动画和交互能力,也是完全没有问题的。目前支持设置自定义布局的弹窗有:

Confirm弹窗,就是确认和取消弹窗

带输入框的Confirm弹窗

Loading弹窗

带列表的Attach弹窗,Center弹窗和Bottom弹窗

假设,你想使用XPopup的Confirm弹窗,但布局想用自己的,只需要这样设置一下,其他不用动即可:

newXPopup.Builder(getContext()).asConfirm(null,"您可以复用项目已有布局,来使用XPopup强大的交互能力和逻辑封装,弹窗的布局完全由你自己控制。\n"+"需要注意的是:你自己的布局必须提供一些控件Id,否则XPopup找不到控件。","关闭","XPopup牛逼",newOnConfirmListener(){@OverridepublicvoidonConfirm(){toast("clickconfirm");}},null,false,ResourceTable.Layout_my_confim_popup)//绑定已有布局.show();

这样布局就是您自己的了,动画和交互XPopup会帮你完成。但是需要注意的是,你自己提供的布局必须包含一些id,否则XPopup无法找到控件;id必须有,控件你可以随意组合与摆放。具体如下:

Confirm弹窗必须包含的Text以及id有:tv_title,tv_content,tv_cancel,tv_confirm

带输入框的Confirm弹窗在Confirm弹窗基础上需要增加一个id为et_input的TextField

Loading弹窗,如果你想显示一个Loading文字说明,则必须有一个id为tv_title的Text;如果不需要文字说明,则没要求

带列表的弹窗会多一个bindItemLayout()方法用来绑定item布局

其他不在多说,看bindLayout方法说明,会说明要求哪些id

每种内置弹窗的bindLayout和bindItemLayout的要求都在方法说明上,无需记忆,用的时候查看下方法的说明即可。

3.2 自定义弹窗

当你自定义弹窗的时候,需要根据需求选择继承CenterPopupView,BottomPopupView,AttachPopupView/HorizontalAttachPopupView,DrawerPopupView,PartShadowPopupView,FullScreenPopupView,PositionPopupView其中之一。

每种弹窗的功能和使用场景如下:

CenterPopupView:中间弹窗的弹窗,比如:确认取消对话框,Loading弹窗等,如果不满意默认的动画效果,可以设置不同的动画器

BottomPopupView:从底部弹出的弹窗,比如:从底部弹出的分享弹窗,知乎的从底部弹出的评论弹窗,抖音从底部弹出的评论弹窗。这种弹窗带有智能的嵌套滚动和手势拖动

AttachPopupView/HorizontalAttachPopupView:Attach弹窗是需要依附于某个点或者某个Component来显示的弹窗;其中AttachPopupView会出现在目标的上方或者下方。如果希望想要微信朋友圈点赞弹窗那样的效果,出现在目标的左边或者右边,则需要继承 HorizontalAttachPopupView来做

DrawerPopupView:从界面的左边或者右边弹出的像DrawerLayout那样的弹窗,Drawer弹窗本身是横向滑动的,但对PageSlider和ScrollView等横向滑动控件做了兼容,在弹窗内部可以放心使用它们

FullScreenPopupView:全屏弹窗,看起来和Ability 一样。该弹窗其实是继承Center弹窗进行的一种实现,可以设置任意的动画器

ImageViewerPopupView:大图浏览弹窗

PositionPopupView:自由定位弹窗,如果你想让弹窗显示在左上角,或者右上角,或者任意位置,并且不需要依附任何Component,此时你需要它

自定义弹窗只有2个步骤:

一:根据自己的需求编写一个类继承对应的弹窗

二:重写getImplLayoutId()返回弹窗的布局,在onCreate中像Ability那样编写你的逻辑即可

注意:自定义弹窗本质是一个自定义控件,但是只需重写一个参数的构造,其他的不要重写,所有的自定义弹窗都是这样。

3.2.1 自定义Center弹窗classCustomPopupextendsCenterPopupView{//注意:自定义弹窗本质是一个自定义控件,但是只需重写一个参数的构造,其他的不要重写,所有的自定义弹窗都是这样publicCustomPopup(Contextcontext){super(context,null);}//返回自定义弹窗的布局@OverrideprotectedintgetImplLayoutId(){returnResourceTable.Layout_custom_popup;}//执行初始化操作,比如:findComponentById,设置点击,或者任何你弹窗内的业务逻辑@OverrideprotectedvoidonCreate(){super.onCreate();findComponentById(ResourceTable.Id_tv_close).setClickedListener(newClickedListener(){@OverridepublicvoidonClick(Componentcomponent){dismiss();//关闭弹窗}});}//设置最大宽度,看需要而定@OverrideprotectedintgetMaxWidth(){returnsuper.getMaxWidth();}//设置最大高度,看需要而定@OverrideprotectedintgetMaxHeight(){returnsuper.getMaxHeight();}//设置自定义动画器,看需要而定@OverrideprotectedPopupAnimatorgetPopupAnimator(){returnsuper.getPopupAnimator();}//弹窗的宽度,用来动态设定当前弹窗的宽度,受getMaxWidth()限制protectedintgetPopupWidth(){return0;}//弹窗的高度,用来动态设定当前弹窗的高度,受getMaxHeight()限制protectedintgetPopupHeight(){return0;}}

注意:Center弹窗的最大宽度默认是屏幕宽度的0.8,如果你自定义布局的宽度是写死的,有可能超出屏幕宽度的0.8,如果你不想被最大宽度限制,只需要重写方法:

@OverrideprotectedintgetMaxWidth(){return0;//返回0表示不限制最大宽度}

使用自定义弹窗:

newXPopup.Builder(getContext()).asCustom(newCustomPopup(getContext())).show();3.2.2 自定义Attach弹窗publicclassCustomAttachPopup2extendsAttachPopupView{publicCustomAttachPopup2(Contextcontext){super(context,null);}@OverrideprotectedintgetImplLayoutId(){returnResourceTable.Layout_custom_attach_popup2;}//设置状态栏的高度,用以修正自定义位置弹窗的高度@OverrideprotectedintsetStatusBarHeight(){return130;}}3.2.3 自定义DrawerLayout类型弹窗publicclassCustomDrawerPopupViewextendsDrawerPopupView{publicCustomDrawerPopupView(Contextcontext){super(context,null);}@OverrideprotectedintgetImplLayoutId(){returnResourceTable.Layout_custom_list_drawer;}@OverrideprotectedvoidonCreate(){super.onCreate();findComponentById(ResourceTable.Id_btn).setClickedListener(newClickedListener(){@OverridepublicvoidonClick(Componentcomponent){toast("nothing!!!");}});}}

使用自定义的DrawerLayout弹窗:

newXPopup.Builder(getContext()).popupPosition(PopupPosition.Right)//右边.asCustom(newCustomDrawerPopupView(getContext())).show();3.2.4 自定义Bottom类型的弹窗

自定义Bottom类型的弹窗会比较常见,默认Bottom弹窗带有手势交互和嵌套滚动;如果您不想要手势交互可以调用enableDrag(false)方法关闭。

请注意:弹窗的宽高是自适应的,大部分情况下都应该将弹窗布局的高设置为match_content;除非你希望得到一个高度撑满的弹窗。

Demo中有一个模仿知乎评论的实现,代码如下:

publicclassZhihuCommentPopupextendsBottomPopupView{ListContainerlistContainer;publicZhihuCommentPopup(Contextcontext){super(context,null);}@OverrideprotectedintgetImplLayoutId(){returnResourceTable.Layout_custom_bottom_popup;}@OverrideprotectedvoidonCreate(){super.onCreate();listContainer=(ListContainer)findComponentById(ResourceTable.Id_listContainer);ArrayList<String>strings=newArrayList<>();for(inti=0;i<30;i++){strings.add("");}EasyProvidercommonAdapter=newEasyProvider<String>(getContext(),strings,ResourceTable.Layout_adapter_zhihu_comment){@Overrideprotectedvoidbind(ViewHolderholder,StringitemData,finalintposition){}};listContainer.setItemClickedListener(newListContainer.ItemClickedListener(){@OverridepublicvoidonItemClicked(ListContainerlistContainer,Componentcomponent,intposition,longid){dismiss();}});listContainer.setItemProvider(commonAdapter);}//最大高度为Window的0.7@OverrideprotectedintgetMaxHeight(){return(int)(XPopupUtils.getScreenHeight(getContext())*.7f);}}3.2.5 自定义全屏弹窗publicclassCustomFullScreenPopupextendsFullScreenPopupView{publicCustomFullScreenPopup(Contextcontext){super(context,null);}@OverrideprotectedintgetImplLayoutId(){returnResourceTable.Layout_custom_fullscreen_popup;}@OverrideprotectedvoidonCreate(){super.onCreate();//初始化}}3.2.6 自定义ImageViewer弹窗

目前大图浏览弹窗支持在上面添加任意自定义布局和背景颜色,做法是写一个类继承ImageViewerPopupView弹窗,然后重写布局即可。

代码如下:

publicclassCustomImagePopupextendsImageViewerPopupView{publicCustomImagePopup(Contextcontext){super(context,null);}@OverrideprotectedintgetImplLayoutId(){returnResourceTable.Layout_custom_image_viewer_popup;}}

由于是自定义的大图浏览弹窗,就要用自定义弹窗的方式来开启了:

//自定义的弹窗需要用asCustom来显示,之前的asImageViewer这些方法当然不能用了。CustomImagePopupviewerPopup=newCustomImagePopup(getContext());//自定义的ImageViewer弹窗需要自己手动设置相应的属性,必须设置的有srcView,url和imageLoader。viewerPopup.setSingleSrcView(image2,url2);viewerPopup.setXPopupImageLoader(newImageLoader());newXPopup.Builder(getContext()).asCustom(viewerPopup).show();

4.2.7 自定义Position弹窗

publicclassQQMsgPopupextendsPositionPopupView{publicQQMsgPopup(Contextcontext){super(context,null);}@OverrideprotectedintgetImplLayoutId(){returnResourceTable.Layout_popup_qq_msg;}}

自由定位弹窗,默认是显示在屏幕的左上角,你可以通过offsetX()和offsetY()来控制显示位置,如果你希望水平居中,可以用isCenterHorizontal(true)选项来做到。

newXPopup.Builder(getContext()).popupAnimation(PopupAnimation.ScaleAlphaFromCenter).isCenterHorizontal(true).offsetY(200).asCustom(newQQMsgPopup(getContext())).show();3.3 自定义动画

自定义动画已经被设计得非常简单,动画和弹窗是无关的;这意味着你可以将动画设置给内置弹窗或者自定义弹窗。继承PopupAnimator,实现3个方法:

如何初始化动画

动画如何开始

动画如何结束

比如:自定义一个旋转的动画:

classRotateAnimatorextendsPopupAnimator{@OverridepublicvoidinitAnimator(){targetView.setScaleX(0.0f);targetView.setScaleY(0.0f);targetView.setAlpha(0.0f);targetView.setRotation(360.0f);}@OverridepublicvoidanimateShow(){targetView.createAnimatorProperty().rotate(0.0f).scaleX(1.0f).scaleY(1.0f).alpha(1.0f).setDuration(getDuration()).start();}@OverridepublicvoidanimateDismiss(){targetView.createAnimatorProperty().rotate(720.0f).scaleX(0.0f).scaleY(0.0f).alpha(0.0f).setDuration(getDuration()).start();}}

使用自定义动画:

newXPopup.Builder(getContext()).customAnimator(newRotateAnimator()).asConfirm("演示自定义动画","当前的动画是一个自定义的旋转动画,无论是自定义弹窗还是自定义动画,已经被设计得非常简单;这个动画代码只有6行即可完成!",null).show();

不想要动画:

newXPopup.Builder(getContext()).customAnimator(newEmptyAnimator(null)).asConfirm("演示自定义动画","当前的动画是一个自定义的旋转动画,无论是自定义弹窗还是自定义动画,已经被设计得非常简单;这个动画代码只有6行即可完成!",null).show();3.4 常用设置3.4.1 全局设置

1.设置主色调 默认情况下,XPopup的主色为灰色,主色作用于Button文字,TextField边框和光标,Check文字的颜色上。 主色调只需要设置一次即可,可以放在启动页中。

XPopup.setPrimaryColor(getColor(ResourceTable.Color_colorPrimary));

2.设置全局的动画时长 默认情况下,弹窗的动画时长为360毫秒。你可以通过下面的方法进行修改:

XPopup.setAnimationDuration(200);//传入的时长最小为0,动画的时长会影响除Drawer弹窗外的所有弹窗3.4.2 常用设置

所有的设置如下,根据需要使用:

newXPopup.Builder(getContext()).isDestroyOnDismiss(true)//是否在消失的时候销毁资源,默认false。如果你的弹窗对象只使用一次,非常推荐设置这个,可以杜绝内存泄漏。如果会使用多次,千万不要设置.dismissOnBackPressed(true)//按返回键是否关闭弹窗,默认为true.dismissOnTouchOutside(true)//点击外部是否关闭弹窗,默认为true.autoOpenSoftInput(true)//是否弹窗显示的同时打开输入法,只在包含输入框的弹窗内才有效,默认为false.popupAnimation(PopupAnimation.ScaleAlphaFromCenter)//设置内置的动画.customAnimator(null)//设置自定义的动画器.popupPosition(PopupPosition.Right)//手动指定弹窗出现在目标的什么位置,对Attach和Drawer类型弹窗生效.positionByWindowCenter(false)//默认是false,是否以屏幕中心进行定位,默认是false,为false时根据Material范式进行定位,主要影响Attach系列弹窗.offsetX(-10)//弹窗在x方向的偏移量.offsetY(-10)//弹窗在y方向的偏移量.maxWidth(10)//设置弹窗的最大宽度,如果重写弹窗的getMaxWidth(),以重写的为准.maxHeight(10)//设置弹窗的最大高度,如果重写弹窗的getMaxHeight(),以重写的为准.isCenterHorizontal(true)//是否和目标水平居中,比如:默认情况下Attach弹窗依靠着目标的左边或者右边,如果isCenterHorizontal为true,则与目标水平居中对齐.isRequestFocus(false)//默认为true,默认情况下弹窗会抢占焦点,目的是为了响应返回按键按下事件;如果为false,则不抢焦点.enableDrag(true)//是否启用拖拽,默认为true,目前对Bottom和Drawer弹窗有用.isDarkTheme(true)//是否启用暗色主题.borderRadius(10)//为弹窗设置圆角,默认是15,对内置弹窗生效.autoDismiss(false)//操作完毕后是否自动关闭弹窗,默认为true;比如点击ConfirmPopup的确认按钮,默认自动关闭;如果为false,则不会关闭.setPopupCallback(newSimpleCallback(){//设置显示和隐藏的回调@OverridepublicvoidonCreated(BasePopupViewbasePopupView){//弹窗内部onCreate执行完调用}@OverridepublicvoidbeforeShow(BasePopupViewbasePopupView){//每次show之前都会执行}@OverridepublicvoidonShow(BasePopupViewbasePopupView){//完全显示的时候执行}@OverridepublicvoidonDismiss(BasePopupViewbasePopupView){//完全隐藏的时候执行}//如果你自己想拦截返回按键事件,则重写这个方法,返回true即可@OverridepublicbooleanonBackPressed(BasePopupViewbasePopupView){newToastDialog(getContext()).setText("我拦截的返回按键,按返回键XPopup不会关闭了").show();returntrue;//默认返回false}//监听弹窗拖拽,适用于能拖拽的弹窗@OverridepublicvoidonDrag(BasePopupViewpopupView,intvalue,floatpercent,booleanupOrLeft){}}).asXXX()//所有的设置项都要写在asXXX()方法调用之前

上述内容就是弹窗库XPopup组件怎么用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。

域名注册
购买VPS主机

您或许对下面这些文章有兴趣:                    本月吐槽辛苦排行榜

看贴要回贴有N种理由!看帖不回贴的后果你懂得的!


评论内容 (*必填):
(Ctrl + Enter提交)   

部落快速搜索栏

各类专题梳理

网站导航栏

X
返回顶部