How would you create a popover view in Android, like Facebook Comments?

后端 未结 5 1396
渐次进展
渐次进展 2021-01-29 23:06

I was wondering if anyone knows how to create a Facebook-like popover view like in the Facebook Android app for comments.

This is what I mean:

5条回答
  •  情歌与酒
    2021-01-29 23:53

    The best way to create similar popover view is by using PopupWindow, since you can place the PopUpWindow on any of the specific view position (or on center/top/bottom of screen). You can also achieve same UI with DialogFragment , but you cannot position at specific view location.

    I have a complete working code here https://gist.github.com/libinbensin/67fcc43a7344758390c3

    Step 1: Create your custom layout , for e.g., as Facebook its has a Header TextView with a ListView and EditText.

    Step 2: Set the layout to the PopupWindow

    Inflate the layout to set

    LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View inflatedView = layoutInflater.inflate(R.layout.fb_popup_layout, null,false);
    

    This Layout has a ListView ,so find the ListView in the layout and fill the data . you can have your own view here

    ListView listView = (ListView)inflatedView.findViewById(R.id.commentsListView);
    listView.setAdapter(new ArrayAdapter(TryMeActivity.this,
            R.layout.fb_comments_list_item, android.R.id.text1,contactsList));
    

    Now, create an instance of PopupWindow with specific height and width. I prefer to set the size depends on the device.

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    
    popWindow = new PopupWindow(inflatedView, size.x - 50,size.y - 500, true );
    

    Set the focusability of the popup window.

    popWindow.setFocusable(true);
    

    Make it outside touchable to dismiss the popup window when touched outside the popup area

    popWindow.setOutsideTouchable(true);
    

    Now, set a background to the PopupWindow with a drawable. The drawable has rectangle shape with corner radius.

      popWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.fb_popup_bg));
    

    Finally. show the PopupWindow at required location. I made it show at bottom of the screen with some X and Y position

    popWindow.showAtLocation(v, Gravity.BOTTOM, 0,150);  // 0 - X postion and 150 - Y position
    

    You can also set an Animation to use when the PopUpWindow appears and disappears

    popWindow.setAnimationStyle(R.anim.animation); // call this before showing the popup
    

    enter image description here

提交回复
热议问题