Basic use of PopupWindow (floating box)


Introduction to this section:

This section brings you the last UI control used to display information-PopupWindow (suspended box), if you want to know What does he look like? You can open QQ on your phone, long press an item in the list, and a small black message will pop up. Dialog box, this kind is PopupWindow. Different from AlertDialog dialog box, its position can be arbitrary;

In addition, AlertDialog is non-thread blocking, while PopupWindow is thread blocking! The official has this sentence to introduce PopupWindow:

A popup window that can be used to display an arbitrary view. The popup window is

a floating container that appears on top of the current activity.

Probably means: a pop-up window control that can be used to display any View and will float on top of the current activity

Let’s learn about this control ~

Official document: PopupWindow


1. Interpretation of related methods


1) Several commonly used construction methods

We can see in the document that there are as many as nine construction methods of PopupWindow provided to us. Only the actual ones are posted here. Several construction methods that are commonly used in development:

  • public PopupWindow (Context context)
  • public PopupWindow(View contentView, int width , int height)
  • public PopupWindow(View contentView)
  • ##public PopupWindow(View contentView, int width, int height, boolean focusable)
There is no need to explain the parameters. contentView is the View displayed by PopupWindow. Whether focusable displays focus


2) Some commonly used methods

The following introduces some of the more commonly used methods. For others, you can consult the documentation yourself:

  • setContentView(View contentView): Set the View displayed by PopupWindow
  • getContentView(): Get the View displayed by PopupWindow
  • showAsDropDown(View anchor): relative to the position of a certain control (directly lower left), no offset
  • showAsDropDown(View anchor, int xoff, int yoff) : There is an offset relative to the position of a certain control
  • showAtLocation(View parent, int gravity, int x, int y): Relative to the position of the parent control (such as Gravity.CENTER in the center, Gravity.BOTTOM below, etc.), you can set an offset or no offset. PS: The parent parameter only needs to be the view in the activity!
  • setWidth/setHeight: Set the width and height. You can also specify the width and height in the construction method. In addition to writing specific values, you can also use WRAP_CONTENT or MATCH_PARENT. The width and height properties of popupWindow directly correspond to the first-layer View.
  • setFocusable(true): Set focus. After PopupWindow pops up, all touch screens and physical buttons are controlled by PopupWindows. deal with. The response to any other events must occur after the PopupWindow disappears (except system-level events such as home). For example, when a PopupWindow like this appears, pressing the back key will first make the PopupWindow disappear, and pressing it a second time will exit. Activity, to be precise, if you want to exit the activity, you must first make the PopupWindow disappear, because the PopupWindow will not disappear under any circumstances when you press back. It must be when the background of the PopupWindow is set.
  • setAnimationStyle(int): Set animation effect

##2. Run using code example

Rendering :

1.gif

Implementation key code :

First paste the animation file:

anim_pop.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android. com/apk/res/android">
; alpha android:fromAlpha="0"
android:toAlpha="1"
android:duration="2000">
< /alpha>
</set>

接着是popupWindow的布局:item_popip.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"
    android:background="../style/images/ic_pop_bg"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_xixi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="嘻嘻"
        android:textSize="18sp" />

    <Button
        android:id="@+id/btn_hehe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="呵呵"
        android:textSize="18sp" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button btn_show;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        btn_show = (Button) findViewById(R.id.btn_show);
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initPopWindow(v);
            }
        });
    }


    private void initPopWindow(View v) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_popup, null, false);
        Button btn_xixi = (Button) view.findViewById(R.id.btn_xixi);
        Button btn_hehe = (Button) view.findViewById(R.id.btn_hehe);
        //1.构造一个PopupWindow,参数依次是加载的View,宽高
        final PopupWindow popWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popWindow.setAnimationStyle(R.anim.anim_pop);  //设置加载动画

        //这些为了点击非PopupWindow区域,PopupWindow会消失的,如果没有下面的
        //代码的话,你会发现,当你把PopupWindow显示出来了,无论你按多少次后退键
        //PopupWindow并不会关闭,而且退不出程序,加上下述代码可以解决这个问题
popWindow.setTouchable(true);
popWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
re turn false;
/ / If true is returned here, the touch event will be intercepted
                                                                                                                                                                        ColorDrawable(0x00000000)); //Set a background for the popWindow to be effective


//Set the position of the popupWindow display. The parameters are the reference View, the offset of the x-axis, and the offset of the y-axis. Shift amount
popWindow.showAsDropDown(v, 50, 0);

//Set the event of the button in popupWindow
btn_xixi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "You clicked hehe~", Toast.LENGTH_SHORT).show();
}
});
btn_hehe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, " You clicked haha~", Toast .LENGTH_SHORT).show();
popWindow.dismiss();
}
       });
      }
}

3. Sample code download

PopWindowDemo.zip


Summary of this section:

Due to time constraints, I didn’t think of a better example, so I wrote a simple demo, which should be able to meet simple needs. In addition, If you want to study PopupWindow in depth, you can read the following references:
Use and Analysis of Android PopupWindow
Detailed Explanation of Android PopupWindow
Well, that’s all, thank you~