Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the XPopup component of pop-up window library

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article shows you how to use the pop-up library XPopup components, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

1. Introduction

XPopup is a pop-up library, which is probably the best pop-up library for the Harmony platform. It is designed on the basis of practical principles, taking into account both beautiful and elegant interaction. Users all like the natural and comfortable UI and interaction, hope XPopup can bring you some help or surprise!

two。 Depends on allprojects {repositories {mavenCentral ()}} implementation 'io.openharmony.tpc.thirdlib:XPopup:1.0.3'3. How to use 3.1.1 to display the confirmation and cancellation dialog box new XPopup.Builder (getContext ()) .asConfirm ("I am the title", "I am the content", new OnConfirmListener () {@ Override public void onConfirm () {toast ("click confirm");}}) .show () 3.1.2 display the confirmation and cancellation dialog box for the input box new XPopup.Builder (getContext ()) .asInputConfirm ("I am the title", "Please enter the content." , new OnInputConfirmListener () {@ Override public void onConfirm (String text) {toast ("input text:" + text) }) .show () 3.1.3 display the pop-up window new XPopup.Builder (getContext ()) / / .maxWidth (600) .asCenterList ("Please choose one", new String [] {"item 1", "item 2", "item 3", "item 4"}) New OnSelectListener () {@ Override public void onSelect (int position, String text) {toast ("click" + text) }}) .show (); 3.1.4 shows the loading box new XPopup.Builder (getContext ()) .asLoading ("loading") that pops up in the middle. 3.1.5 display the pop-up window new XPopup.Builder (getContext ()) .asBottomList ("Please choose one", new String [] {"item 1", "item 2", "item 3", "item 4", "item 5"}, new OnSelectListener () {@ Override public void onSelect (int position)) that pops up from the bottom String text) {toast ("click" + text) }) .show () 3.1.6 displays the pop-up window new XPopup.Builder (getContext ()) .atView (component) / / attached to the Component clicked on a Component or a point The internal will automatically judge that .asAttachList (new String [] {"share", "edit", "without icon"}, new int [] {ResourceTable.Media_icon, ResourceTable.Media_icon}, new OnSelectListener () {@ Override public void onSelect (int position) is displayed above or below. String text) {toast ("click" + text) }) .show ()

If you want to attach to a touch point of a Component, you need to watch the Component first, and then display it when you click or long press the trigger:

Component component = findComponentById (ResourceTable.Id_btnShowAttachPoint); / / this method must be called to monitor View's touch final XPopup.Builder builder = new XPopup.Builder (getContext ()) .watchView (component) before the event occurs. Component.setLongClickedListener (new LongClickedListener () {@ Override public void onLongClicked (Component component) {builder.asAttachList (new String [] {"Top", "copy", "delete"}, null, new OnSelectListener () {@ Override public void onSelect (int position, String text) {toast ("click" + text) }) .show ();})

Inside the asAttachList method is the encapsulation of AttachPopupView. If your layout is not a list, you can inherit the layout you want from AttachPopupView. AttachPopupView will appear above or below the target. If you want to appear on the left or right side of the target (like a like pop-up window on Wechat moments), you can inherit HorizontalAttachPopupView and write your layout.

The simplest examples are as follows:

Public class CustomAttachPopup extends HorizontalAttachPopupView {public CustomAttachPopup (Context context) {super (context, null);} @ Override protected int getImplLayoutId () {return ResourceTable.Layout_custom_attach_popup;} @ Override protected void onCreate () {super.onCreate () FindComponentById (ResourceTable.Id_tv_zan) .setClickedListener (new ClickedListener () {@ Override public void onClick (Component component) {ToastUtil.showToast (getContext (), "like"); dismiss ();}}) FindComponentById (ResourceTable.Id_tv_comment) .setClickedListener (new ClickedListener () {@ Override public void onClick (Component component) {ToastUtil.showToast (getContext (), "comments"); dismiss ();}}) } / / set the height of the status bar to correct the height of the custom location pop-up window @ Override protected int setStatusBarHeight () {return 130 } 3.1.7 display large picture browsing pop-up window / / execute the following code when you click on the picture: / / multiple picture scenarios (you have multiple pictures to browse) new XPopup.Builder (getContext ()) .asImageViewer (image, position, list) New OnSrcViewUpdateListener () {@ Override public void onSrcViewUpdate (ImageViewerPopupView popupView, int position) {/ / pager updates the currently displayed picture / / when isInfinite is enabled The position will grow infinitely and needs to be mapped to the page int realPosi = position% list.size () in the current ViewPager Pager.setCurrentPage (realPosi, false);}}, new ImageLoader (). Show (); / / single image scene new XPopup.Builder (getContext ()) .asImageViewer (image, url, new ImageLoader ()) .show () / / Image loader. XPopup is not responsible for loading pictures. You need to implement a picture loader to send it to me. Here, take Glide and OkGo (which can be copied directly to the project): class ImageLoader implements XPopupImageLoader {@ Override public void loadImage (int position, String url, Image imageView) {/ / load pictures as soon as you enter the page. Need to add a little delay context.getUITaskDispatcher () .delayDispatch (new Runnable () {@ Override public void run () {Glide.with (context) .load (url) .diskCacheStrategy (DiskCacheStrategy.ALL) .into (image)) }, 50); / / this method must be implemented to download pictures. Can refer to the following implementation, internal preservation of the picture will be used. If you don't need to save pictures, you can return null. @ Override public File getImageFile (Context context, String url) {try {return OkGo.get (url) .tag (this) .converter (new FileConvert ()) .adapt () .execute () .body ();} catch (Exception e) {LogUtil.error (TAG, e.getMessage ());} return null;}}

If you are not using Glide, please refer to the implementation.

3.1.8 close the pop-up window

Get the pop-up object first. Take the Loading pop-up window as an example, and the rest are the same:

BasePopupView popupView = new XPopup.Builder (getContext ()) .asLoading ("loading") .show ()

Execution disappears:

/ / there are four ways to disappear: popupView.dismiss (); / immediately disappear popupView.delayDismiss (300); / / delay disappears. Sometimes the experience of disappearing too fast may not be good, so you can delay popupView.smartDismiss (); / / wait for the start animation of the pop-up window to finish execution before disappearing, which can prevent the animation from being incomplete caused by calling the API too quickly. PopupView.dismissWith ({}); / / execute some logic after the execution of the vanishing animation

In a project, we often click a button and close the pop-up window, and then do something. For example: click a button, close the pop-up window, and then open an interface. You should know that there is an animation process when the pop-up window is closed. The above description shows that you will jump to the page immediately before the pop-up window is completely closed, and the interface has a sudden sense of frustration; and when the equipment resources are insufficient, it may also cause frame loss. So in many cases, it is not recommended to use the dismiss () method directly, unless there is no logical execution after you close the pop-up window.

For the best experience, you can wait until the dismiss animation is completely over to perform something, rather than immediately. You can do this:

PopupView.dismissWith (new Runnable () {@ Override public void run () {/ / Jump to New Page}})

Each pop-up window itself has lifecycle callbacks for onShow () and onDismiss (), which can be used as needed.

There is also a scenario where after the pop-up window show () is finished, your logic is finished, and then dismiss () is called. But your logic is executed too fast, which may lead to the direct dismiss of the pop-up window's show animation before it is finished, and the feeling on the interface is not good. At this time, it is recommended to use the smartDismiss () method, which ensures that the pop-up window is closed after the execution of the show animation.

3.1.9 existing layout of the reuse project

If you already have a written pop-up layout in your project, and you want to use the animation and interaction capabilities provided by XPopup, there is no problem at all. Currently, pop-up windows that support custom layout are as follows:

Confirm pop-up window, which is to confirm and cancel the pop-up window

Confirm pop-up window with input box

Loading pop-up window

Attach pop-up window, Center pop-up window and Bottom pop-up window with list

Suppose you want to use XPopup's Confirm pop-up window, but the layout wants to use your own. You just need to set it this way, and you don't have to move anything else:

New XPopup.Builder (getContext ()) .asConfirm (null, "you can reuse the existing layout of the project to use the powerful interaction and logical encapsulation of XPopup, and the layout of the pop-up window is completely under your own control.\ n" + "it is important to note that your own layout must provide some controls Id, otherwise XPopup will not find the controls." , "close", "XPopup awesome", new OnConfirmListener () {@ Override public void onConfirm () {toast ("click confirm") }}, null, false, ResourceTable.Layout_my_confim_popup) / / bind existing layouts .show ()

The layout is your own, and animation and interactive XPopup will help you do it. It is important to note, however, that the layout you provide must contain some id, otherwise XPopup cannot find controls; id must have controls that you can combine and place at will. The details are as follows:

The Text and id that the Confirm pop-up window must contain are: tv_title,tv_content,tv_cancel,tv_confirm

The Confirm pop-up window with input box needs to add a TextField with id as et_input on the basis of Confirm pop-up window.

Loading pop-up window, if you want to display a Loading text description, you must have a Text; with id of tv_title. If you do not need a text description, it is not required.

The pop-up window with list will have an additional bindItemLayout () method to bind the item layout.

If you look at the description of the bindLayout method, it will indicate which id is required.

The bindLayout and bindItemLayout requirements of each built-in pop-up window are on the method description. You don't need to remember it. Just check the method description when you use it.

3.2 Custom pop-up window

When you customize the pop-up window, you need to choose to inherit one of the CenterPopupView,BottomPopupView,AttachPopupView/HorizontalAttachPopupView,DrawerPopupView,PartShadowPopupView,FullScreenPopupView,PositionPopupView according to your requirements.

The functions and usage scenarios of each pop-up window are as follows:

CenterPopupView: pop-up window in the middle, such as confirm cancel dialog box, Loading pop-up window, etc. If you are not satisfied with the default animation effect, you can set different animators.

BottomPopupView: pop-up windows that pop up from the bottom, such as: share pop-up window that pops up from the bottom, Zhihu pop-up window that pops up from the bottom, Douyin comment pop-up window that pops up from the bottom. This pop-up window has intelligent nested scrolling and gesture dragging.

An AttachPopupView/HorizontalAttachPopupView:Attach pop-up window is a pop-up window that needs to be attached to a point or a Component to display; where the AttachPopupView appears above or below the target. If you want the like pop-up window on Wechat moments to appear on the left or right side of the target, you need to inherit HorizontalAttachPopupView to do it.

DrawerPopupView: pop-up windows like DrawerLayout pop up from the left or right side of the interface. The Drawer pop-up window itself is horizontal sliding, but it is compatible with horizontal sliding controls such as PageSlider and ScrollView, so you can rest assured to use them inside the pop-up window.

FullScreenPopupView: full screen pop-up window, which looks the same as Ability. The pop-up window is actually an implementation that inherits the Center pop-up window, and any animator can be set up.

ImageViewerPopupView: big picture browsing pop-up window

PositionPopupView: freely locate the pop-up window. If you want the pop-up window to be displayed in the upper left corner, or the upper right corner, or anywhere, and you don't need to attach any Component, you need it.

There are only 2 steps to customize the pop-up window:

One: write a pop-up window corresponding to class inheritance according to your own needs

Second: rewrite the layout of the getImplLayoutId () return pop-up window and write your logic like Ability in onCreate.

Note: the custom pop-up window is essentially a custom control, but you only need to rewrite the construction of one parameter, and don't rewrite the rest, as is the case with all custom pop-up windows.

3.2.1 Custom Center pop-up window class CustomPopup extends CenterPopupView {/ / Note: custom pop-up window is essentially a custom control, but only need to rewrite the construction of one parameter, other do not rewrite, all custom pop-up windows are like this public CustomPopup (Context context) {super (context, null) } / / return the layout of the custom pop-up window @ Override protected int getImplLayoutId () {return ResourceTable.Layout_custom_popup;} / / perform initialization operations, such as: findComponentById, set click, or any business logic @ Override protected void onCreate () {super.onCreate () in your pop-up window FindComponentById (ResourceTable.Id_tv_close) .setClickedListener (new ClickedListener () {@ Override public void onClick (Component component) {dismiss (); / / close the pop-up window}});} / / set the maximum width, depending on the need @ Override protected int getMaxWidth () {return super.getMaxWidth () } / / set the maximum height, as needed @ Override protected int getMaxHeight () {return super.getMaxHeight ();} / / set custom animator, and depending on need @ Override protected PopupAnimator getPopupAnimator () {return super.getPopupAnimator () } / / the width of the pop-up window, which is used to dynamically set the width of the current pop-up window. Restricted by getMaxWidth (), the height of protected int getPopupWidth () {return 0;} / / pop-up window is used to dynamically set the height of the current pop-up window, and protected int getPopupHeight () {return 0;}} is restricted by getMaxHeight ().

Note: the maximum width of the Center pop-up window is 0.8% of the screen width by default. If the width of your custom layout is written to death, it may exceed 0.8% of the screen width. If you do not want to be limited by the maximum width, just rewrite the method:

@ Overrideprotected int getMaxWidth () {return 0; / / returns 0 to indicate no limit on the maximum width}

Use a custom pop-up window:

New XPopup.Builder (getContext ()) .asCustom (new CustomPopup (getContext () .show (); 3.2.2 Custom Attach pop-up window public class CustomAttachPopup2 extends AttachPopupView {public CustomAttachPopup2 (Context context) {super (context, null);} @ Override protected int getImplLayoutId () {return ResourceTable.Layout_custom_attach_popup2 } / / set the height of the status bar to correct the height of the custom location pop-up window @ Override protected int setStatusBarHeight () {return 130;}} 3.2.3 Custom DrawerLayout type pop-up window public class CustomDrawerPopupView extends DrawerPopupView {public CustomDrawerPopupView (Context context) {super (context, null);} @ Override protected int getImplLayoutId () {return ResourceTable.Layout_custom_list_drawer } @ Override protected void onCreate () {super.onCreate (); findComponentById (ResourceTable.Id_btn) .setClickedListener (new ClickedListener () {@ Override public void onClick (Component component) {toast ("nothingcake!");}});}}

Use a custom DrawerLayout pop-up window:

New XPopup.Builder (getContext ()) .popupPosition (PopupPosition.Right) / / right .asCustom (new CustomDrawerPopupView (getContext () .show (); 3.2.4 customize the pop-up window of Bottom type

Custom Bottom type pop-up windows are more common, the default Bottom pop-up window with gesture interaction and nested scrolling; if you do not want gesture interaction can be turned off by calling the enableDrag (false) method.

Please note that the width and height of the pop-up window is adaptive, and in most cases you should set the height of the pop-up layout to match_content; unless you want to get a highly full pop-up window.

There is an implementation in Demo that imitates Zhihu comments. The code is as follows:

Public class ZhihuCommentPopup extends BottomPopupView {ListContainer listContainer; public ZhihuCommentPopup (Context context) {super (context, null);} @ Override protected int getImplLayoutId () {return ResourceTable.Layout_custom_bottom_popup;} @ Override protected void onCreate () {super.onCreate (); listContainer = (ListContainer) findComponentById (ResourceTable.Id_listContainer); ArrayList strings = new ArrayList () For (int I = 0; I < 30; iTunes +) {strings.add ("");} EasyProvider commonAdapter = new EasyProvider (getContext (), strings, ResourceTable.Layout_adapter_zhihu_comment) {@ Override protected void bind (ViewHolder holder, String itemData, final int position) {}} ListContainer.setItemClickedListener (new ListContainer.ItemClickedListener () {@ Override public void onItemClicked (ListContainer listContainer, Component component, int position, long id) {dismiss ();}}); listContainer.setItemProvider (commonAdapter) } / / maximum height of Window @ Override protected int getMaxHeight () {return (int) (XPopupUtils.getScreenHeight (getContext ()) * .7f);} 3.2.5 Custom full-screen pop-up window public class CustomFullScreenPopup extends FullScreenPopupView {public CustomFullScreenPopup (Context context) {super (context, null) } @ Override protected int getImplLayoutId () {return ResourceTable.Layout_custom_fullscreen_popup;} @ Override protected void onCreate () {super.onCreate (); / / initialization} 3.2.6 Custom ImageViewer pop-up window

Currently, the large image browsing pop-up window supports adding any custom layout and background color to it. The practice is to write a class that inherits the ImageViewerPopupView pop-up window, and then rewrite the layout.

The code is as follows:

Public class CustomImagePopup extends ImageViewerPopupView {public CustomImagePopup (Context context) {super (context, null);} @ Override protected int getImplLayoutId () {return ResourceTable.Layout_custom_image_viewer_popup;}}

Since it is a custom large image browsing pop-up window, it is necessary to use a custom pop-up window to open it:

/ / Custom pop-up windows need to be displayed with asCustom. Of course, these methods cannot be used by the previous asImageViewer. CustomImagePopup viewerPopup = new CustomImagePopup (getContext ()); / / the custom ImageViewer pop-up window needs to set the corresponding properties manually, such as srcView,url and imageLoader. ViewerPopup.setSingleSrcView (image2, url2); viewerPopup.setXPopupImageLoader (new ImageLoader ()); new XPopup.Builder (getContext ()) .asCustom (viewerPopup) .show ()

4.2.7 Custom Position pop-up window

Public class QQMsgPopup extends PositionPopupView {public QQMsgPopup (Context context) {super (context, null);} @ Override protected int getImplLayoutId () {return ResourceTable.Layout_popup_qq_msg;}}

Free positioning pop-up window, the default is displayed in the upper left corner of the screen, you can use offsetX () and offsetY () to control the display position, if you want to center horizontally, you can use the isCenterHorizontal (true) option.

New XPopup.Builder (getContext ()) .popupAnimation (PopupAnimation.ScaleAlphaFromCenter) .isCenterhorizontal (true) .offsetY (2000.asCustom (new QQMsgPopup (getContext () .show (); 3.3.Custom animation

Custom animation has been designed to be very simple, and animation has nothing to do with pop-up windows; this means that you can set the animation to built-in pop-up windows or custom pop-up windows. Inherit PopupAnimator and implement three methods:

How to initialize an animation

How to start Animation

How does the animation end

For example: customize a rotating animation:

Class RotateAnimator extends PopupAnimator {@ Override public void initAnimator () {targetView.setScaleX (0.0f); targetView.setScaleY (0.0f); targetView.setAlpha (0.0f); targetView.setRotation (360.0f);} @ Override public void animateShow () {targetView.createAnimatorProperty (). Rotate (0.0f) .scaleX (1.0f) .scaleY (1.0f) .alpha (1.0f) .setDuration (getDuration ()). Start () } @ Override public void animateDismiss () {targetView.createAnimatorProperty () .rotate (720.0f) .scaleX (0.0f) .scaley (0.0f) .alpha (0.0f) .setDuration (getDuration ()) .start ();}}

Use custom animation:

New XPopup.Builder (getContext ()) .customAnimator (new RotateAnimator ()) .asConfirm ("demonstrate custom animation", "the current animation is a custom rotation animation, whether it is a custom pop-up window or a custom animation, it has been designed to be very simple; this animation code can be completed in only six lines!" , null) .show ()

Do not want animation:

New XPopup.Builder (getContext ()) .customAnimator (new EmptyAnimator (null)) .asConfirm ("demonstrate custom animation", "the current animation is a custom rotation animation, whether it is a custom pop-up window or a custom animation, it has been designed to be very simple; this animation code can be completed in only six lines!" , null) .show (); 3.4 Common Settings 3.4.1 Global Settings

1. Set the dominant tone by default, the dominant color of XPopup is gray, which acts on the color of Button text, TextField borders and cursors, and Check text. The main tone only needs to be set once and can be placed on the startup page.

XPopup.setPrimaryColor (getColor (ResourceTable.Color_colorPrimary))

two。 Set the global animation duration by default, the pop-up window is animated for 360 milliseconds. You can modify it in the following ways:

XPopup.setAnimationDuration; / / the minimum input time is 0, and the animation duration will affect all the pop-up window 3.4.2 common settings except the Drawer pop-up window.

All the settings are as follows, use as needed:

New XPopup.Builder (getContext ()) .isDestroyOnDiscover (true) / / whether to destroy the resource when it disappears. Default is false. If your pop-up object is only used once, it is highly recommended to set this to prevent memory leaks. If you can use it multiple times, never set .dismissOnBackPack (true) / / whether to close the pop-up window by pressing the return key. The default is true .dismissOnTouchOutside (true) / / whether to close the pop-up window by clicking on the outside. The default is true .autoOpentInput (true) / / whether to open the input method while displaying the pop-up window. It is only valid in the pop-up window that contains the input box. The default is false .popupAnimation (PopupAnimation.ScaleAlphaFromCenter) / / sets the built-in animation .customAnimator (null) / / sets the custom animator .popupPosition (PopupPosition.Right) / / manually specifies where the pop-up window appears in the target, and takes effect on Attach and Drawer pop-up windows. PositionByWindowCenter (false) / / defaults to false, whether to position in the center of the screen, and defaults to false. When the false is positioned according to the Material normal form, it mainly affects the offset of the Attach series pop-up window .offsetX (- 10) / / pop-up window in the x direction. OffsetY (- 10) / / the offset of the pop-up window in the y direction. MaxWidth (10) / sets the maximum width of the pop-up window. If the getMaxWidth () of the pop-up window is overwritten, the maximum height of the pop-up window shall prevail. MaxHeight (10) / sets the maximum height of the pop-up window. If you override the getMaxHeight () of the pop-up window, if the overridden .isCenterhorizontal (true) / / is centered with the target level, for example, by default, the Attach pop-up window depends on the left or right side of the target, and if isCenterHorizontal is true, it is aligned with the target horizontal. IsRequestFocus (false) / / is true by default, and the pop-up window grabs the focus by default in response to the return keystroke event. If it is false, it does not grab the focus. EnableDrag (true) / / whether to enable drag and drop is true, which is currently useful for Bottom and Drawer pop-up windows. IsDarkTheme (true) / / whether to enable dark theme. BorderRadius (10) / / sets fillets for pop-up windows. Default is 15. It takes effect on built-in pop-up windows. Autodiscards (false) / / automatically closes pop-up windows after operation. Default is true. For example, click the confirm button of ConfirmPopup, which is automatically turned off by default. If it is false The .setPopupCallback (new SimpleCallback () {/ / sets the callback @ Override public void onCreated (BasePopupView basePopupView) {/ / the internal onCreate of the pop-up window is finished) @ Override public void beforeShow (BasePopupView basePopupView) {/ / is not closed. Execute} @ Override public void onShow (BasePopupView basePopupView) {/ / when fully displayed} @ Override public void onDismiss (BasePopupView basePopupView) {/ / completely hidden before each show } / / if you want to intercept the return button event yourself Override this method and return true to @ Override public boolean onBackPressed (BasePopupView basePopupView) {new ToastDialog (getContext ()) .setText ("I blocked the return button, pressing the return key XPopup will not close") .show () Return true / / false is returned by default / / monitor pop-up window drag and drop Applicable to the drag-and-drop pop-up window @ Override public void onDrag (BasePopupView popupView, int value, float percent,boolean upOrLeft) {}}) .asXXX () / all settings should be written before the asXXX () method call, the above is how to use the pop-up library XPopup component, have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report