SoFunction
Updated on 2025-04-09

Android imitates Toast to achieve prompt box effect

This article shares the specific code for Android imitating Toast to realize the effect of prompt box for your reference. The specific content is as follows

Toast prompts can float on any other interface as long as the prompt is long enough, so we can imitate Toast to implement the prompt box of the incoming call number's home location.

1、WindowManager

The interface that apps use to talk to the window manager. Use (Context.WINDOW_SERVICE) to get one of these. Each window manager instance is bound to a particular Display.

1).void addView(View view, params)
LayoutParams are used by views to tell their parents how they want to be laid out.

2).void removeView(View view); Removes a View view from the current window.

2. Custom form prompt box (refer to Toast source code)

WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); 
View view = (getApplicationContext(), .toast_location,
                null); 
TextView tv = (TextView) (.tv_toast_address);
(address);
LayoutParams params = new LayoutParams();
 = .WRAP_CONTENT;
 = .WRAP_CONTENT;
 =  | ;
 = ("lastx", 0);
 = ("lasty", 0);
//There was originally a FLAG_NOTUCHALBE to remove this in order to allow the bottom to touch. = .FLAG_NOT_FOCUSABLE| .FLAG_KEEP_SCREEN_ON;
 = ;    //In the source code, here is TYPE_TAOST, but here is to perform a click-and-drag event, but Toast cannot be dragged.So here it's changedTYPE_PRIORITY_PHONE,This is a system type prompt box,Use this prompt box to apply for permission,.SYSTEM_ALERT_WINDOW
 = .TYPE_PRIORITY_PHONE; 
(view, params); 

3. Simple drag of the display box added by WindowManager

This View registers an onTouchListener

public void showLocation(String address) {
    view = (getApplicationContext(), .toast_location,
            null);
    // Get spint which = ("which", 0);    (bgs[which]);
    (new OnTouchListener() {
        int startX ,startY;

        public boolean onTouch(View v, MotionEvent event) {
            switch (()) {

            case MotionEvent.ACTION_DOWN:(TAG,"Touched");
                startX = (int) ();
                startY  = (int) ();
                break;
            case MotionEvent.ACTION_MOVE:(TAG,"move");
                int newX = (int) ();
                int newY  = (int) ();
                int dx = newX - startX;
                int dy = newY - startY;
                +=dx;
                +=dy;   //The layout method cannot be used in WindowManager. It is invalid. You can only use layoutparams to update the location. The params here are the params above.                (view, params);
                //Reinitialize the finger position                startX = (int) ();
                startY  = (int) ();
                break;
            }
            return true;
        }
    });
}

4. Drag the normal ImageView with your finger to change the position

iv_drag_view.setOnTouchListener(new OnTouchListener() {
    //Record the position when the initial finger was pressed int startX , startY;    // If the return value of the onTouch method is true, the listener will consume this event, false, the listener will not consume this event public boolean onTouch(View v, MotionEvent event) {        switch (()) {  
            case MotionEvent.ACTION_DOWN:(TAG,"Touched this control");
                startX = (int) ();//Record the distance from the x and y axis when the finger clicks on the screen for the first time                startY = (int) ();
            break;
            case MotionEvent.ACTION_MOVE:// Events of finger moving on the screen (TAG, "move");                int newX = (int) (); //During the process of moving, I constantly get the position where the finger is currently moving to int newY = (int) ();                int dx = newX - startX;           //Calculate how much the finger has moved int dy = newY - startY;                int l = iv_drag_view.getLeft(); //Get the length of the image up, down, left and right, int r = iv_drag_view.getRight();                int b = iv_drag_view.getBottom();
                int t = iv_drag_view.getTop();

                int newl = l+dx; // Calculate the distance the picture should move int newr = r+dx;                int newt = t+dy;//imageview New position in the form int newb = b+dy;
                //Judge if the position where the picture is about to move beyond the screen, do not allow it to move. Here 30 is the height of the status bar above the form if (newl<0||newt < 0 ||newb>()-30||newr>()){                    break;
                }            
                //Move the image to a new location.  Directly call the layout method of ImageView                iv_drag_view.layout(newl,  newt, newr, newb); 
                // Once the picture is moved to a new position, recalculate the current position of the finger, so that the cycle can be carried out with the finger dragging                startX = (int) ();
                startY = (int) ();
            break;
            case MotionEvent.ACTION_UP: // The corresponding event of the fingers leaving the screen the moment they leave. (TAG, "let go");            int lasty = iv_drag_view.getTop();//Get the last distance from the top of the screen int lastx = iv_drag_view.getLeft();//Get the last distance from the left of the screen Editor editor = ();            ("lastx", lastx);
            ("lasty", lasty);
            ();
            break;
        }
            return true; //This place must return true to tell the system that the event has been completed    }
});

Notice:There is no effect when using the layout method in the onCreate method, because when entering an activity, the system will first perform a calculation operation, calculate the layout of each control, and then call the setContentView method to display the control. The layout method will be executed in the second step. However, the layout is set in the onCreate method. When executing the layout code, the form may not have calculated the layout of the control, so the layout is executed first, and then the control layout is executed to display it. In this way, the layout is invalid. How can I do it here? Only by setting the layout layout of this control, so that it can be calculated when calculating the position. This setting of the layout allows it to be calculated when calculating. As follows, set this in the onCreate method.

protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    sp = getSharedPreferences("config", MODE_PRIVATE);
    // Have the system blur any windows behind this one.
    getWindow().setFlags(.FLAG_BLUR_BEHIND,
            .FLAG_BLUR_BEHIND);
    wm = (WindowManager) getSystemService(WINDOW_SERVICE);//Form Manager    display = ();

    setContentView(.activity_drag_view);
    tv_drag_view = (TextView) findViewById(.tv_drag_view);
    iv_drag_view = (ImageView) findViewById(.iv_drag_view);

    int lastx = ("lastx", 0);
    int lasty = ("lasty", 0);

     params = (LayoutParams) iv_drag_view.getLayoutParams();
     = lastx;
     = lasty;
    iv_drag_view.setLayoutParams(params); 
}

Notice:In WindowManager, if you want to update the distance of the control, you cannot use the layout method, you can only use (view, params);

5. Implement double-click event

1).Double-click definition There is no double-click click event provided in Android. Double-click is two clicks in a unit time

2). The difference between touch and click events Click events: A collection of sets of actions Click - Stay - Leave. Touch events: Press the screen with fingers Finger moves on the screen The moment the finger leaves the screen

public class DragViewActivity extends Activity {
    protected static final String TAG = "DragViewActivity";
    private ImageView iv_drag_view;
    private TextView tv_drag_view;
    private SharedPreferences sp;

    private WindowManager wm;
    private Display  display; //The resolution of the display of the form private long firstClickTime;//The event @Overrideprotected void onCreate(Bundle savedInstanceState) {        (savedInstanceState);
        sp = getSharedPreferences("config", MODE_PRIVATE);
        // Have the system blur any windows behind this one.
        getWindow().setFlags(.FLAG_BLUR_BEHIND,
                .FLAG_BLUR_BEHIND);
        wm = (WindowManager) getSystemService(WINDOW_SERVICE);//Form Manager        display = ();

        setContentView(.activity_drag_view);
        tv_drag_view = (TextView) findViewById(.tv_drag_view);
        iv_drag_view = (ImageView) findViewById(.iv_drag_view);

        int lastx = ("lastx", 0);
        int lasty = ("lasty", 0);

         params = (LayoutParams) iv_drag_view.getLayoutParams();
         = lastx;
         = lasty;
        iv_drag_view.setLayoutParams(params);

        iv_drag_view.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                (TAG,"Clicked.");
                if(firstClickTime&gt;0){//It means this is the second click.long secondTime = ();                    long dtime = secondTime - firstClickTime;
                    if(dtime&lt;500){
                        //Double-click event.(TAG, "Double-click center");                        int iv_width = iv_drag_view.getRight() - iv_drag_view.getLeft();
                        iv_drag_view.layout(()/2-iv_width/2, iv_drag_view.getTop(), ()/2+iv_width/2, iv_drag_view.getBottom());
                        int lasty = iv_drag_view.getTop();//Get the last distance from the top of the screen int lastx = iv_drag_view.getLeft();//Get the last distance from the left of the screen Editor editor = ();                        ("lastx", lastx);
                        ("lasty", lasty);
                        ();
                    }
                    firstClickTime = 0;//Restore the first click time to 0.  return;                } else {
                //First click                    firstClickTime = ();// Record the time of the first click// A new thread is opened. If there is no clicking in this child thread within 500 milliseconds, the time of the first click is set to 0new Thread(){                        public void run() {
                            try {
                                (500);
                                firstClickTime = 0;
                            } catch (InterruptedException e) {
                                ();
                            }
                        };
                    }.start();
                }               
            }
        });
    }
}

6. Return value when touch and double-click occur simultaneously

//The return value of the onTouch method, True if the listener has consumed the event, false otherwise,true The listener will consume this event, false will not consume this eventiv_drag_view.setOnTouchListener(new OnTouchListener() {

    int startX , startY;
    public boolean onTouch(View v, MotionEvent event) {
        switch (()) {
        case MotionEvent.ACTION_DOWN:// Event when your finger touches the screen (TAG, "Touch this control");            startX = (int) ();
            startY = (int) ();
            break;
        case MotionEvent.ACTION_MOVE:// Events of finger moving on the screen (TAG, "move");            int newX = (int) ();
            int newY = (int) ();
            int dx = newX - startX;
            int dy = newY - startY;
            int l = iv_drag_view.getLeft();
            int r = iv_drag_view.getRight();
            int b = iv_drag_view.getBottom();
            int t = iv_drag_view.getTop();

            int newl = l+dx;
            int newr = r+dx;
            int newt = t+dy;//imageview New position in the form int newb = b+dy;
            if(newl&lt;0||newt &lt; 0 ||newb&gt;()-30||newr&gt;()){
                break;
            }

            int tv_height = tv_drag_view.getBottom() - tv_drag_view.getTop();

            if(newt&gt;()/2){//imageview is below the form //textview is above the form                tv_drag_view.layout(tv_drag_view.getLeft(), 0, tv_drag_view.getRight(), tv_height);
            }else{
                tv_drag_view.layout(tv_drag_view.getLeft(), ()-tv_height-30, tv_drag_view.getRight(), ()-30);
                //textview is below the form            }

            iv_drag_view.layout(newl,  newt, newr, newb);

            //Update the starting position of the finger.            startX = (int) ();
            startY = (int) ();
            break;
        case MotionEvent.ACTION_UP: // The corresponding event of the fingers leaving the screen the moment they leave. (TAG, "let go");            int lasty = iv_drag_view.getTop();//Get the last distance from the top of the screen int lastx = iv_drag_view.getLeft();//Get the last distance from the left of the screen Editor editor = ();            ("lastx", lastx);
            ("lasty", lasty);
            ();
            break;
        }
        // Here, the touch event should return true. Why is it returned here? Because this control implements both click and touch events at the same time. If true, // Then it is impossible to happen. Therefore, the return value of the control that implements click and touch at the same time must be falsereturn false;    }
});

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.