单击浮动操作按钮时,属性android:onClick =“ FabOnClick”使应用程序崩溃

时间:2019-05-09 14:36:14

标签: xamarin.android visual-studio-2017

使用Xamarin for Visual Studio的人似乎并不多,因此那里没有很多专门针对该平台的信息。

话虽如此,我一直在尝试使“浮动操作按钮”(FAB)起作用,这确实是一项练习。我终于得到它的出现,并在使用StackOverflow的好伙伴的帮助下将其分配给活动中的变量,但无法获得android:onClick="FabOnClick"调用来工作。单击FAB会导致应用崩溃,并显示以下错误:

Unhandled Exception:
Java.Lang.IllegalStateException: Could not find method FabOnClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.design.widget.FloatingActionButton with id 'fab' occurred

这是我活动中的代码:

    public void FabOnClick(View v)
    {
        int x = 1;
    }

它实际上并没有任何作用,因为我现在只是试图捕获click事件。我在int x = 1行上设置了一个断点,以查看其执行时间。那我想念什么?

*更新*

我根据以下@ Digitalsa1nt的答案更新了活动代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Acr.UserDialogs;
using Android.Net;
using System.Net;
using Android.Support.Design.Widget;
using System.Threading.Tasks;
using Android.Views.InputMethods;
using static Android.Views.View;

namespace OML_Android
{
    [Activity(Label = "CreateAccount")]
    public class CreateAccount : Activity
    {
        public string result = "";
        public EditText aTextboxUsername;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.CreateAccount);

            RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;


            aTextboxUsername = FindViewById<EditText>(Resource.Id.aTextboxUsername);
            EditText aTextboxPassword = FindViewById<EditText>(Resource.Id.aTextboxPassword);
            EditText aTextboxPassword2 = FindViewById<EditText>(Resource.Id.aTextboxPassword2);
            EditText txtEmailAddress = FindViewById<EditText>(Resource.Id.txtEmailAddress);
            EditText txtEmailAddress2 = FindViewById<EditText>(Resource.Id.txtEmailAddress2);

            EditText txtFirstName = FindViewById<EditText>(Resource.Id.first_name);
            EditText txtMI = FindViewById<EditText>(Resource.Id.mi);
            EditText txtLastName =  FindViewById<EditText>(Resource.Id.last_name);
            EditText txtAddress =  FindViewById<EditText>(Resource.Id.address);
            EditText txtCity = FindViewById<EditText>(Resource.Id.city);
            Spinner spnState =  FindViewById<Spinner>(Resource.Id.state);
            EditText txtZip = FindViewById<EditText>(Resource.Id.zip);
            MaskedEditText.MaskedEditText txtPhone = FindViewById<MaskedEditText.MaskedEditText>(Resource.Id.phone);
            Spinner spnCompany = FindViewById<Spinner>(Resource.Id.company_spinner);
            Spinner spnDept = FindViewById<Spinner>(Resource.Id.department_spinner);
            Spinner spnSection = FindViewById<Spinner>(Resource.Id.section_spinner);

            Button ButtonSubmit = FindViewById<Button>(Resource.Id.button_submit);
            ScrollView sv = FindViewById<ScrollView>(Resource.Id.scrollView1);
            ButtonSubmit.SetBackgroundColor(Android.Graphics.Color.YellowGreen);

            // Hide the keyboard (also doesn't work)
            InputMethodManager board = (InputMethodManager)GetSystemService(Context.InputMethodService);
            board.HideSoftInputFromWindow(aTextboxUsername.WindowToken, 0);


            // get the floating action button.
            FloatingActionButton myFab = FindViewById< FloatingActionButton>(Resource.Id.fab);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            DataInterfaceWeb.DataInterface myService = new DataInterfaceWeb.DataInterface();


            myFab.Click += FabButton_Click(); // <-- get error here
            try
            {

                ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);

                NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
                bool isOnline = (activeConnection != null) && activeConnection.IsConnected;

                if (!isOnline)
                {
                    showMessage("There is no internet or cell phone connection.  Connect to a network or connect to a cellular network.", "ERROR");
                }
            }
            catch (Exception ex)
            {
                showMessage("Connectivity Manager failed to create a connection due to error: " + ex.Message, "ERROR");
            };

            // Create your application here

            ButtonSubmit.Click += async (sender, e) =>
            {
                try
                {
                    result = myService.CheckForUser(Master.username, Master.password, aTextboxUsername.Text);
                    if (result.ToUpper() == "Y")
                    {
                        await showMessage("Username " + aTextboxUsername.Text + " is already in use.  Please choose another", "ERROR");
                        // aTextboxUsername.SetSelectAllOnFocus(true);
                        aTextboxUsername.RequestFocus();
                        View insideView = FindViewById<EditText>(Resource.Id.aTextboxUsername);
                        sv.ScrollTo(0, (int)insideView.GetY());
                        aTextboxUsername.SelectAll();
                    }

                }
                catch (Exception ex)
                {
                    showMessage("Account creation attempt failed due to error: " + ex.Message, "ERROR");
                }
            };

        }
        public async Task showMessage(string message, string messageType)
        {

            var result = await UserDialogs.Instance.ConfirmAsync(new ConfirmConfig
            {
                Message = messageType + System.Environment.NewLine + message,
                OkText = "Ok",

            });
        }
        public void FabButton_Click()
        {
            int x = 1;
        }
    }
}

我现在得到的错误是:     无法在行myFab.Click += FabButton_Click();上将'void'隐式转换为'SystemEventHandler'。

2 个答案:

答案 0 :(得分:1)

@ Digitalsa1nt确实指出了正确的方向。代替

fabButton.Click += FabButton_Click;

我刚刚组织了一个活动,错误提示(duh):

myFab.Click += (sender, e) =>
{
    FabButton_Click();
};

现在可以正常运行了。

答案 1 :(得分:0)

所以我在这个答案中做了两个假设。首先,您正在使用Xamarin.Native项目,而不是Xamarin.Forms项目。

第二,我假设您正在使用以下一种支持库中的FloatingActionButton:Android.Support.Design.Widget(基本/ V4 / V7)。

在“ AXML布局”页面中定义FAB之后:

<android.support.design.widget.FloatingActionButton
      app:backgroundTint="@color/colourPrimary"
      android:id="@+id/fabButton"
      android:src="@drawable/image"
      app:fabSize="normal"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:elevation="16dp"
      android:translationZ="12dp"
      app:rippleColor="#ffa9a9a9" />

您可以从自己的活动中获取它,例如:

using Android.Support.Design.Widget;

// declare variable
private FloatingActionButton fabButton;

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    // call base
    base.OnCreateView(inflater, container, savedInstanceState);

    // inflate our view
    var view = inflater.Inflate(Resource.Layout.MainTabWishlistPage, container, false);

    // get our instance of the button using the resource ID.
    fabButton = view.FindViewById<FloatingActionButton>(Resource.Id.fabButton);

    // assign to click event
    fabButton.Click += FabButton_Click;
}

private void FabButton_Click(object sender, EventArgs e)
{
     int x = 1;
}

以上示例基于片段而不是活动,但是方法相同。

官方Git回购: Xamarin/monodroid-samples - Floating Action Button Basic

随机在线指南: android-material-design-floating-action

如果这是Xamarin.Forms项目,请查看James Montemagno的库(ps是Xamarin上的开发人员之一,并创建了大量的库来帮助您简化生活,绝对可以通过他的其他存储库查看。)

jamesmontemagno/FloatingActionButton-for-Xamarin.Android