Xamarin Android Snackbar NullReferenceException

Xamarin Android Snackbar NullReferenceException

我想展示一个小吃店:

Snackbar s = Snackbar
                .Make(Window.DecorView.RootView, text, Snackbar.LengthLong)
                .SetAction("Retry", view =>
                {
                    /* TODO */
                });
s.Show();

我在调用方法时收到 NullReferenceException

Object reference not set to an instance of an object.

我做错了什么?

我们遇到了类似的问题。尽管我们遵循了文档,但我们不断收到 NullReferenceException,结果证明是 父布局视图。

就我而言,它在我 清理并构建 我的 Visual Studio 项目后起作用。

请参阅下面我的代码以供参考:

我有以下带有 id 引用的父级线性布局 loginView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:id="@+id/loginView"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <!-- omitted --> 

    </LinearLayout>
</LinearLayout>

接下来,我有一个实用程序 class,方法如下:

/// <summary>
/// Show a snackbar notification on screen
/// </summary>
/// <param name="view">this is the parent container</param>
/// <param name="msg">message to show in the snackbar</param>
public static void ShowSnack(View view, string msg)
{            
    if(view != null)
    {
        try
        {
            Snackbar snackBar = Snackbar.Make(view, msg, Snackbar.LengthLong);
            snackBar.SetAction("Ok", (v) =>
            {
                Log.Info(TAG, "Action in view clicked");
            });
            snackBar.Show();
        }
        catch(Exception ex)
        {
            Log.Error(TAG, "Error occured when showing snackbar: " + ex.Message); 
        }                
    }
}

最后,我可以使用以下内容显示 activity 中的 SnackBar:

var view = FindViewById(Resource.Id.loginView);
AndroidUtil.ShowSnack(view, "Hey there it works!");

更多信息:

我们目前使用的是 Visual Studio 2017 RC。我们注意到的一件事是我们不得不经常清理项目,因为这是很常见的事情。