在 recyclerview 中的正确位置显示警报对话框

displaying alert dialog in the correct location within a recyclerview

我正在制作一个自定义按钮,当您长按它时,会出现一个对话框,其中包含可供选择的选项列表。

自定义按钮可以正常工作,但是,我在调整对话框以使其准确显示在我想要的位置时遇到了一些问题。

这是显示对话框的代码。

private void ShowReactionsDialog()
{
    var context = Context;
    var inflater = (LayoutInflater) context.GetSystemService(Context.LayoutInflaterService);
    var dialogView = inflater.Inflate(Resource.Layout.react_dialog_layout, null);
    var linearLayoutManager = new LinearLayoutManager(context)
    {
        Orientation = LinearLayoutManager.Horizontal
    };
    var adapter = new ReactionAdapter(_reactionList);

    adapter.OnItemClicked += (sender, currentReaction) =>
    {
        UpdateReactButtonByReaction(currentReaction);

        _reactAlertDialog.Cancel();
    };

    var rvReactions = dialogView.FindViewById<RecyclerView>(Resource.Id.reaction_rvReactions);

    rvReactions.HasFixedSize = true;
    rvReactions.SetLayoutManager(linearLayoutManager);
    rvReactions.SetItemAnimator(new DefaultItemAnimator());
    rvReactions.SetAdapter(adapter);

    var dialogBuilder = new AlertDialog.Builder(context);
    dialogBuilder.SetView(dialogView);

    _reactAlertDialog = dialogBuilder.Create();
    _reactAlertDialog.RequestWindowFeature((int)WindowFeatures.NoTitle);

    var window = _reactAlertDialog.Window;
    window.SetBackgroundDrawableResource(Resource.Drawable.react_dialog_shape);
    window.SetDimAmount(0);

    // Setup dialog gravity and dynamic position
    var windowManagerAttributes = window.Attributes;
    windowManagerAttributes.Gravity = GravityFlags.AxisSpecified;
    windowManagerAttributes.X = (int) GetX() + (Width / 2);
    windowManagerAttributes.Y = (int) GetY() + (Height / 2);

    _reactAlertDialog.Show();

    var dialogWidth = GetIconSize() * _reactionList.Count;

    if (dialogWidth > GetScreenMaxWidth())
    {
        dialogWidth = GetScreenMaxWidth();
    }

    window.SetLayout(dialogWidth, ViewGroup.LayoutParams.WrapContent);
}

我试过弄乱重力和 X 和 Y 坐标,但它只是想要么太高要么太低,它没有坚持一致的位置。我希望它位于长按按钮上方。

您可以使用以下代码使 AlertDialog 显示在按钮上方。

int[] location = new int[2];
AndroidX.AppCompat.App.AlertDialog alertDialog = builder.Create();
Window window = alertDialog.Window;
WindowManagerLayoutParams attributes = window.Attributes;
//Get the location of the button and location[0] is X and location[1] is Y
button.GetLocationInWindow(location);
//Set the height of the AlertDialog
int height = 400;
int a = button.Height / 2;
int c = location[1];
//Get the distance of top
attributes.Y = c - a - height;
window.Attributes = attributes;
//Set the AlertDialog location according to the distance of top
window.SetGravity(GravityFlags.Top);
alertDialog.Show();
//Set the Width and Hight of the AlertDialog
alertDialog.Window.SetLayout(800, height);