Getting started with Android series: message prompt box and dialog box

Keywords: Java Android Android Studio Design Pattern

1, Message prompt box and dialog box

1. Use Toast to display the message prompt box

There are contacts before the message prompt box. The main application is

Toast.makeText().show

Next, learn in detail

The objects of the Toast class have the following common methods

setDuration(int duration) sets the duration toast.length of the message_ LONG/SHORT

setGravity(int gravity,int xOffset,int yOffset) sets the position. The parameters are alignment and offset respectively

Setmargin (float horizontal margin, float vertical margin) sets the margin of the message prompt box

Settext (charsequences) sets the display text content

Setview (view) displays the view location

The java code is as follows

package com.thundersoft.session2;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class ToastActivity extends Activity {
    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout linearLayout = new LinearLayout(ToastActivity.this);
        Toast.makeText(this, "Toast The first way to create", Toast.LENGTH_SHORT).show();
        setContentView(linearLayout);

        LinearLayout linearLayout1 = new LinearLayout(ToastActivity.this);
        ImageView imageView = new ImageView(ToastActivity.this);
        imageView.setImageResource(R.drawable.gif1);
        imageView.setPadding(0,0,5,0);
        imageView.setLayoutParams(new LinearLayout.LayoutParams(300,300));
        TextView textView = new TextView(ToastActivity.this);
        textView.setText("Toaset The second way to create");

        Toast toast = new Toast(this);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER,0,0);

        linearLayout1.addView(imageView);
        linearLayout1.addView(textView);
        linearLayout1.setBackgroundColor(R.color.purple_200);
        toast.setView(linearLayout1);
        toast.show();
    }
}

There are two layouts in the code. The first layout is the general layout, that is, the first page, and the second layout is the layout applied in Toaset

2. Use Notification to display notifications on the status bar

After Android 8, API26

Android's Notification management classes are Notification and notificationmanager classes

Notification is mainly a class representing the global effect, while Manager mainly manages sending notification, which is a system service

The following is the method of general notification implementation

package com.thundersoft.session2;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

public class NotificationActivity extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout linearLayout = new LinearLayout(this);
        setContentView(linearLayout);

        Button button = new Button(this);
        linearLayout.addView(button);

        final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//        Custom channel id
        String id = "channel_1";
//        Custom channel description properties
        String description = "channel_description";
        int NOTIFY_ID_1=0x1;
        int NOTIFY_ID_2=0x2;
//        Channel sound prompt
        int importance = NotificationManager.IMPORTANCE_HIGH;

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Create notification channel class
                NotificationChannel channel = new NotificationChannel(id, "123", importance);
//                Set description properties
                channel.setDescription(description);
//                Turn on the flash
                channel.enableLights(true);
//                Open vibration
                channel.enableVibration(true);
                channel.setVibrationPattern(new long[]{100,200,300,400,500,400,300,200,400});
//                Manager create channel
                manager.createNotificationChannel(channel);
//                Create notification object
                Notification builder = new Notification.Builder(NotificationActivity.this, id)
//                        title
                        .setContentTitle("Notice title")
//                        small icons
                        .setSmallIcon(R.drawable.gif1)
//                        Large icon
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.gif1))
//                        content
                        .setContentText("Notice column content")
//                        Set auto delete notification
                        .setAutoCancel(true)
//                        structure
                        .build();
//                Keep multiline notifications, unique number required
                manager.notify(NOTIFY_ID_1,builder);
            }
        });
    }
}

Firstly, the notification needs to define several values: the id of the notification channel, its description attribute, and its number

After defining the value, first obtain the system service and new a notification management object

Then, new notifies the channel object, sets its various properties, and gives the channel to the notification management object for management

When the channel is set, start the new notification object, call the Builder method of the class to build and set the properties

Finally, give the notice to the management object for management

The general notification click will automatically jump to a page. An intent is written here to realize the function of click notification jump

Intent intent = new Intent(Notification2Activity.this, NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(Notification2Activity.this, 0, intent, 0);
Notification builder2 = new Notification.Builder(Notification2Activity.this, id)
        .setContentTitle("Notice title")
        .setSmallIcon(R.drawable.gif1)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.gif1))
        .setContentText("Notice column content")
        .setAutoCancel(true)
        .setContentIntent(pendingIntent)
        .build()
        ;
manager.notify(NOTIFY_ID_2,builder2);

You need a new intent, and then use it pendingintent to convey the intent. The intent will be explained in detail later

The cancellation of notification can be controlled by the following codes

manager.cancel(NOTIFY_ID_1);
manager.cancelAll();

3. Use AlertDialog to create a dialog box

The following describes the four commonly used dialog boxes

The application steps of the dialog box are: through new AlertDialog.Builder, set its properties and buttons, and finally don't forget to create and show

Create four new buttons corresponding to four dialog boxes. Write the first and most basic dialog box. The code is as follows

package com.thundersoft.session2;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

public class AlertDialogActivity extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout linearLayout = new LinearLayout(this);
        setContentView(linearLayout);
        Button button1 = new Button(this);
        Button button2 = new Button(this);
        Button button3 = new Button(this);
        Button button4 = new Button(this);
        button1.setText("Button dialog box");
        button2.setText("tabbed dialog box ");
        button3.setText("list+Button dialog box");
        button4.setText("Multiple choice+Button dialog box");
        linearLayout.addView(button1);
        linearLayout.addView(button2);
        linearLayout.addView(button3);
        linearLayout.addView(button4);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
                alertDialog.setIcon(R.drawable.gif1);
                alertDialog.setTitle("Tip 1:");
                alertDialog.setMessage("Cancellation, neutrality and determination");
//        inactive
                alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i("dialog box","Click Cancel");
                    }
                });
//        positive
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "determine", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i("dialog box","Click OK");
                    }
                });
//        neutral
                alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "neutral", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i("dialog box","Click neutral");
                    }
                });
                alertDialog.show();
            }
        });

Two, three or four are as follows

button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] strings = {"Article 1", "Article 2", "Article 3", "Article 4"};
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
                alertDialog.setTitle("Tip 2:");
                alertDialog.setItems(strings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i("dialog box", "onClick: "+strings[which]);
                    }
                });
                alertDialog.create().show();
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] strings = {"Article 1", "Article 2", "Article 3", "Article 4"};
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
                alertDialog.setTitle("Tip 3:");
                alertDialog.setSingleChoiceItems(strings, 0,new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i("dialog box", "onClick: "+strings[which]);
                    }
                });
                alertDialog.setPositiveButton("determine",null);
                alertDialog.create().show();
            }
        });
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean[] items = {false,false,true,true};
                String[] strings = {"Article 1", "Article 2", "Article 3", "Article 4"};
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
                alertDialog.setTitle("Tip 3:");
                alertDialog.setMultiChoiceItems(strings, items, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        items[which] = isChecked;
                    }
                });
                alertDialog.setPositiveButton("determine", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String result = "";
                        for (int i = 0; i < items.length; i++) {
                            if (items[i]){
                                result+=strings[i]+",";
                            }
                        }
                        if (!"".equals(result)){
                            result = result.substring(0,result.length()-1);
                            Log.i("dialog box", result);
                        }
                    }
                });
                alertDialog.create().show();
            }
        });
    }
}

In the fourth method, a button is added, and new DialogInterface.OnClickListener() is directly added in the button to create a new click event

The following code demonstrates the exit confirmation dialog prompt

package com.thundersoft.session2;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

public class Test1Activity extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout linearLayout = new LinearLayout(this);
        setContentView(linearLayout);

        Button button = new Button(this);
        button.setText("Click exit");
        linearLayout.addView(button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(Test1Activity.this);
                builder.setIcon(R.drawable.gif1);
                builder.setTitle("Exit?");
                builder.setMessage("Do you really want to exit code?");
                builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.setPositiveButton("determine", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                builder.create().show();
            }
        });

    }
}

2, Practice

1. Requirements

A login page is implemented, which provides the function of remembering password and user name. After login, the list view must include login user name, and clicking the list will display the item clicked

(the above are the practical requirements of Android)

On the previous practice project, after logging in, select the first option in the main interface list to display a group of pictures. Before the pictures are loaded, a progress bar needs to be displayed. After the loading is completed, long press a picture to pop up a prompt box whether to delete it. If yes, the picture will not be displayed.

2. Code implementation

image.xml page displaying pictures

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <GridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:stretchMode="columnWidth"
        android:numColumns="3"
        android:id="@+id/gridview"/>
</LinearLayout>

items.xml contents of each gridview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/imageview"
        android:scaleType="fitXY"
        android:paddingLeft="10px"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5px"
        android:layout_gravity="center"
        android:id="@+id/titleview"/>
</LinearLayout>

title.xml custom title bar

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Image preview"
        android:textStyle="bold"
        android:textColor="#FFFF0000"
        />
    <ProgressBar
        android:id="@+id/bartest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"
        android:max="80"/>
</LinearLayout>

In the last practice, you need to change the following code of MainActivity.java

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    int index = position+1;
    if (index == 1){
        Intent intent = new Intent(MainActivity.this, ImageActivity.class);
        startActivity(intent);
    }
    Toast.makeText(this,"You have selected No"+ index +"term",Toast.LENGTH_SHORT).show();
}

The main part is ImageActivity

package com.thundersoft.login;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ImageActivity extends Activity {

    int[] image = new int[]{R.drawable.jpg1,R.drawable.jpg2,R.drawable.jpg3,R.drawable.jpg4,R.drawable.jpg5};
    String[] title = {"Avatar 1", "Avatar 2", "Avatar 3", "Avatar 4", "Avatar 5"};
    ArrayList<Map<String, Object>> list = new ArrayList<>();
    private ProgressBar progressBar;
    private GridView gridView;
    private SimpleAdapter simpleAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

        setContentView(R.layout.image);

        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.title);
        progressBar = findViewById(R.id.bartest);
        gridView = findViewById(R.id.gridview);

        new MyTack().execute();

        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(ImageActivity.this, "position" + position, Toast.LENGTH_SHORT).show();

                AlertDialog.Builder builder = new AlertDialog.Builder(ImageActivity.this);
                builder.setTitle("Delete?");
                builder.setMessage("Are you sure you want to delete it?");
                builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.setPositiveButton("determine", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        list.remove(position);
                        simpleAdapter.notifyDataSetChanged();
                    }
                });
                builder.create().show();

                return true;
            }
        });
    }
    class MyTack extends AsyncTask<Void,Integer,SimpleAdapter>{
        @Override
        protected SimpleAdapter doInBackground(Void... params) {
            for (int i = 0; i < image.length; i++) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("imageview",image[i]);
                map.put("titleview",title[i]);

                try {
                    list.add(map);
                    Thread.sleep(600);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                publishProgress(i);
            }
            simpleAdapter = new SimpleAdapter(ImageActivity.this,
                    list,
                    R.layout.items,
                    new String[]{"titleview", "imageview"},
                    new int[]{R.id.titleview, R.id.imageview});
            return simpleAdapter;
        }
        //        publishProgress
        @Override
        protected void onProgressUpdate(Integer... values) {
            progressBar.setProgress(values[0]*20);
            super.onProgressUpdate(values);
        }
        @Override
        protected void onPostExecute(SimpleAdapter result) {
            progressBar.setVisibility(View.GONE);
//            setProgressBarVisibility(false);

            gridView.setAdapter(result);
//            linearLayout.addView(result);
            super.onPostExecute(result);
        }
    }
}

Describe the running process of the code in detail

Pass the intent of the previous page to this page and start the oncreate method

Load custom title bar, set page, find control and other basic operations

Next, perform thread operation. Write Tack to inherit AsyncTask. Note that the result parameter should be SimpleAdapter and implement the three methods

The doInBackground method returns a SimpleAdapter. In this, create a SimpleAdapter object, load pictures and text into the adapter, and return the adapter

The onProgressUpdate method displays the update operation and shows the user the progress

onPostExecute method parameter, result should be a SimpleAdapter object, through gridView.setAdapter(result); To load the adapter into gridview

After the thread operation is completed, display gridview, set long press and click operation for each element, and display a dialog box to ask for deletion. The deletion is completed in the overloaded adapter through the operation of list

3. Achieve results

Posted by bluetonic on Sun, 28 Nov 2021 18:10:46 -0800