创建类似popover view 的最佳方法是使用PopupWindow,因为您可以将PopUpWindow 放置在任何特定视图位置(或屏幕的中心/顶部/底部)。您也可以使用 DialogFragment 实现相同的 UI,但您不能定位在特定的视图位置。
我这里有一个完整的工作代码https://gist.github.com/libinbensin/67fcc43a7344758390c3
第 1 步: 创建您的自定义布局,例如,Facebook 有一个 Header TextView 和一个 ListView 和 EditText。
第 2 步: 将布局设置为 PopupWindow
膨胀布局来设置
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View inflatedView = layoutInflater.inflate(R.layout.fb_popup_layout, null,false);
这个Layout有一个ListView,所以在布局中找到ListView并填充数据。你可以在这里有自己的看法
ListView listView = (ListView)inflatedView.findViewById(R.id.commentsListView);
listView.setAdapter(new ArrayAdapter<String>(TryMeActivity.this,
R.layout.fb_comments_list_item, android.R.id.text1,contactsList));
现在,创建一个具有特定高度和宽度的PopupWindow 实例。我更喜欢根据设备设置大小。
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
popWindow = new PopupWindow(inflatedView, size.x - 50,size.y - 500, true );
设置弹窗的focusability。
popWindow.setFocusable(true);
让它在可触摸的to dismiss the popup window when touched outside弹出区域之外
popWindow.setOutsideTouchable(true);
现在,使用可绘制对象为 PopupWindow 设置背景。可绘制对象具有rectangle shape 和corner radius。
popWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.fb_popup_bg));
最后。在所需位置显示PopupWindow。我让它显示在屏幕的bottom 和一些X and Y position
popWindow.showAtLocation(v, Gravity.BOTTOM, 0,150); // 0 - X postion and 150 - Y position
您还可以设置Animation 在PopUpWindow 出现和消失时使用
popWindow.setAnimationStyle(R.anim.animation); // call this before showing the popup