preface

Popovers are an essential part of the graphical interface. Remember those awful bad popovers in Windows, making them more efficient and user-friendly is essential. There are two popular popover classes, PopupWindow and AlertDialog. PopupWindow is a random popup that can pop up anywhere, like the little popover you see in the “like” section of friends. An AlertDialog is a very serious one, with a fixed location in the center. For example, it is used for annoying update notifications, most of which are message title + content + OK button + cancel button. All right, without further ado.


PopupWindow

Official document portal

Instance analysis

Let’s take a look at a general PopupWindow usage and then look at it line by line.

PopupWindow popupWindow = new PopupWindow();

popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(View.inflate(this, R.layout.layout_popup, null));

popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(false);

popupWindow.setAnimationStyle(R.style.anim_menu_bottombar);

popupWindow.showAsDropDown(bt_popup, 0, 0);
Copy the code

Resolution:

  • The first thing to do is create a PopupWindow object. Of course, there are many constructors that take arguments, and no arguments is the best one to understand.
  • Then, set the triplet, set the width and height, and set the layout View. If you want to display a popover, these three sentences are necessary.
  • thenpopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));On higher versions of Android (e.g. 8.0), this is ok, but not on lower versions (e.g. 4.1), which will result in a return click or other part of the screen not being able to cancel the popover, so it’s safe to add it and set it to a transparent color.
  • popupWindow.setFocusable(true);It’s important, it’s usually true, so after the popover, the focus goes to the popover, you click on something else, the popover loses focus and it goes away.popupWindow.setOutsideTouchable(false);True and false have almost the same effect if the previous statement is true.
  • The next step is to add an animation effect, which you can use either by default or custom.
  • The last line shows the popover, aligned to the lower left by default, and the last two parameters are offset values. Then let’s look at a rendering.


Content added

RelativeLayout rl_content = (RelativeLayout) findViewById(R.id.rl_content);
popupWindow.showAtLocation(rl_content, Gravity.CENTER, 0, 0);
Copy the code

Supplement:

  • There is another way to display showAtLocation(). For example, get a layout and set Gravity.CENTER and offset in the code above, which will place the popover at the CENTER of the layout plus the offset.

AlertDialog

Official document portal

Instance analysis

Resolution:

  • Let’s take a look at build.gradle in the ModuleThe compile 'com. Android. Support: appcompat - v7:25.3.1'Make sure the version is larger than 22, since 22 introduced a Material Design style Dialog(Material Design introduced in 5.0). Of course, if you use Android Studio, this is probably not a concern.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com. Android. Support. Test. Espresso: espresso - core: 2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com. Android. Support: appcompat - v7:25.3.1'
    compile 'com. Android. Support. The constraint, the constraint - layout: 1.0.2'
    testCompile 'junit: junit: 4.12'
}
Copy the code
  • In addition, the following two sentences are different. The second instantiation method will cause the style inconsistency between pre-5.0 and post-5.0. Here are two renderings. Using API16 virtual machines.

android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);

AlertDialog.Builder builder = new AlertDialog.Builder(this);

  • Okay, let’s move on to the text. Let’s build the simplest popover. Of course, the following code can be condensed into one line of code, but it’s not intuitive, and I prefer cleaner code.
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);

builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle("title");
builder.setMessage("message");

builder.setPositiveButton("positive", null);
builder.setNegativeButton("negative", null);
builder.setNeutralButton("neutral", null);

builder.setCancelable(true);
android.support.v7.app.AlertDialog dialog = builder.create();
dialog.show();
Copy the code

  • One thing to notice is,setPositiveButtonThe second argument is actually a listener, you can do as follows.
builder.setPositiveButton("positive", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
	    Toast.makeText(getApplicationContext(), "positive", Toast.LENGTH_SHORT).show(); }});Copy the code
  • This linebuilder.setCancelable(true);To cancel the popover, click on the part outside the popover. Set false to do so.
  • And then an AlertDialog is very easy to put in all kinds of items, like radio and multiple. But notice, there’s a conflict between these, like beforebuilder.setMessage("message");And setting radio and multiple entries cannot coexist. The code and renderings are shown below. Of course, I didn’t even write the monitor. I’ll do it myself.
builder.setItems(new String[]{"1"."2"."3"}, null);
Copy the code
builder.setSingleChoiceItems(new String[]{"1"."2"."3"}, 2, null); // Numbers are selected by default, starting from 0Copy the code
builder.setMultiChoiceItems(new String[]{"1"."2"."3"}, new boolean[]{true.true.false}, null); // Boolean arrays are checked accordinglyCopy the code


Content added

Supplement:

  • Now let’s do a more complicated one, and a more interesting one. Of course, there are Adapter methods, but I’m not going to write about them in this article, because I use Adapter too much, and I might have to make a separate section next time.

<? xml version="1.0" encoding="utf-8"? > <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <EditText
        android:id="@+id/et_account"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="TextFields" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_account"
        tools:ignore="TextFields" />

    <Button
        android:id="@+id/bt_cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@id/et_password"
        android:text="@string/bt_cancel"
        tools:ignore="RtlHardcoded" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_password"
        android:layout_toLeftOf="@id/bt_cancel"
        android:text="@string/bt_login"
        tools:ignore="RtlHardcoded" />
</RelativeLayout>
Copy the code
  • Write a random layout file and add the following line to Java. The thing is, if you look closely at the renderings, you’ll see that custom views can work withbuilder.setMessage("message");Co-exist, but in fact, it doesn’t seem necessary, so I’m purposely showing some non-custom views, but you can write all your own custom views.
builder.setView(View.inflate(this, R.layout.layout_login, null));
Copy the code

The last

Please remember to click a “like”, if you have any comments or suggestions, you can see them in the comments section. Of course, you can also secretly follow me.