【问题标题】:Xamarin Android Snackbar NullReferenceExceptionXamarin Android Snackbar NullReferenceException
【发布时间】:2017-03-07 13:08:51
【问题描述】:

我正在尝试显示一个小吃店:

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

调用该方法时,我得到一个NullReferenceException

对象引用未设置为对象的实例。

我做错了什么?

【问题讨论】:

  • 通话时text 包含什么内容?为什么您的view =>.SetAction 根本没有填写?缺少信息,这可能是您的代码看到 null 引用(什么都没有)的原因。
  • 啊,好吧,刚刚调试了一遍,发现视图是空的。我通过 DependencyInjection 调用该方法。将 android 视图作为参数传递的正确视图是什么,或者如何获取当前视图?

标签: c# android xamarin.android snackbar


【解决方案1】:

我们遇到了类似的问题。尽管我们遵循了文档,但我们不断收到 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>

接下来,我有一个具有以下方法的实用程序类:

/// <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); 
        }                
    }
}

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

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

更多信息:

我们目前使用的是 Visual Studio 2017 RC。我们注意到的一件事是,我们必须经常清理项目,因为这是经常发生的事情。

【讨论】:

  • 谢谢!由于一些内部设计更改,我们停止使用小吃店,但我仍然会接受您的回答!谢谢你:)
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 2022-11-21
  • 2016-08-06
  • 2017-03-26
  • 2015-08-22
  • 2017-05-10
  • 2019-07-24
  • 2017-09-13
相关资源
最近更新 更多