Home » Android » How to add multiple views to window manager in Android

How to add multiple views to window manager in Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

Android screenshot

I am developing a application like Facebook Chat Heads a know how to add a single view to window manager.

How to add multiple views to window manager? I tried frame layout and relative layout, but how can I move chat head from one place to another place if I am using relative layout?

For adding multiple views I used below code:

chatHead = new ImageView(this);
    chatHead.setImageResource(R.drawable.ic_launcher);
    TextView t = new TextView(this);
    t.setText("Blessan Mathew");
    t.setBackgroundColor(Color.CYAN);
    params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    childLayout.addView(t, params1);

    params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    childLayout.addView(chatHead, params1);
    fr.addView(childLayout);

    params = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_PHONE,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.TRANSLUCENT
    );
    params.gravity = Gravity.TOP | Gravity.LEFT;
    params.x = 0;
    params.y = 100;
    windowManager.addView(fr, params);

How can I drag chat head to remove its view?

How to&Answers:

To add notification on top of ImageView and move both the views together:

Use RelativeLayout as parent Layout and add ImageView and TextView to it.

private RelativeLayout parentlayout;
TextView notification;

chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.deals);
chatHead.setId(imageid);
parentlayout = new RelativeLayout(this);

notification = new TextView(this);
notification.setTextColor(Color.parseColor("#494949"));
notification.setText("1");
notification.setId(nameid);
notification.setTextSize(19);

final RelativeLayout.LayoutParams params_imageview = new RelativeLayout.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT);

params_imageview.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

final RelativeLayout.LayoutParams params_name = new RelativeLayout.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT);

params_name.addRule(RelativeLayout.ALIGN_RIGHT, imageid);
params_name.addRule(RelativeLayout.ALIGN_TOP, imageid);

parentlayout.addView(chatHead, params_imageview);// adding user image to view
parentlayout.addView(notification, params_name);

Finally make these changes:

mWindowManager.updateViewLayout(parentlayout, params);

and

mWindowManager.addView(parentlayout, params);

PS: Use shapes to style TextView and get exact notification as that of Facebook!! 🙂