如何在所需位置显示模型窗口?

时间:2016-04-25 11:14:07

标签: c# android xamarin xamarin.android

我有一个9 * 9的键盘模态窗口。并用它填充数独游戏板。 在android studio中, 获取按钮的位置我使用了以下代码

_selectedButton=(Button)view;

        int tag=(int)_selectedButton.getTag();
        _currentRow=tag/9;
        _currentCol=tag%9;
int[] location=new int[2];
        _selectedButton.getLocationOnScreen(location);
        _p=new Point();
        _p.x=location[0];
        _p.y=location[1];

        ShowKeyBoard();

ShowKeyBoard就像这样

int offsetX=30;
int offsetY=30;
_popupWindow.showAtLocation(_keyBoardLayout, Gravity.NO_GRAVITY, _p.x+offsetX, _p.y+offsetY);

之后他选择了一个键,我关闭了弹出窗口。

public void BtnKey1Pressed(View view)
    {
        _selectedButton.setText("1");
        _popupWindow.dismiss();
    }

我怎么能在Xamarin Android中做到这一点。 是否有可能在xamarin中获得这样的返回数据。?

int selectedKey=ShowKeyBoard();

1 个答案:

答案 0 :(得分:2)

我试图创建一个快速而脏的popupwindow实现。我假设您想要在您单击的按钮上显示弹出窗口,这就是我使用ShowAsDropDown的原因。我留下了GetLocationOnScreen代码,你只需要传递它。

public sealed class MyPopup : PopupWindow
{
    private readonly Action<int> _callbackMethod;

    private MyPopup(Activity context, Action<int> callbackMethod)
        : base(context.LayoutInflater.Inflate(Resource.Layout.Popup, null),
            ViewGroup.LayoutParams.WrapContent,
            ViewGroup.LayoutParams.WrapContent)
    {
        _callbackMethod = callbackMethod;
    }

    public static Task<int> GetNumber(Activity mainActivity, Button button)
    {
        var t = new TaskCompletionSource<int>();
        var popupWindow = new MyPopup(mainActivity, i => t.TrySetResult(i));
        popupWindow.Show(button);
        return t.Task;
    }

    private void Show(View anchor)
    {
        SetActionForChildButtons(anchor, View_Click);
        ShowAsDropDown(anchor);
    }

    private void SetActionForChildButtons(View parent, EventHandler e)
    {
        var button = parent as Button;
        if (button != null)
        {
            button.Click += e;
            return;
        }

        var viewGroup = parent as ViewGroup;
        if (viewGroup == null)
            return;

        for (var i = 0; i < viewGroup.ChildCount; i++)
        {
            var view = viewGroup.GetChildAt(i);
            SetActionForChildButtons(view, e);
        }
    }

    private void View_Click(object sender, EventArgs e)
    {
        var button = sender as Button;
        if (button == null)
            return;

        int number;
        if (int.TryParse(button.Text, out number))
            _callbackMethod?.Invoke(number);

        Dismiss();
    }
}

通过这个你可以得到你的领域的数字,就像这样

private async void OnClick(object sender, EventArgs e)
{
    var button = sender as Button;
    if (button == null)
        return;
    var location = new int[2];
    button.GetLocationOnScreen(location);
    var number = await MyPopup.GetNumber(this, button);
    button.Text = number.ToString();
}