【问题标题】:Xamarin FindViewById NullReference ExceptionXamarin FindViewById NullReference 异常
【发布时间】:2017-12-30 16:37:55
【问题描述】:

我有一个问题,每当我尝试将事件处理程序添加到按钮时,我得到一个空引用异常,我正在尝试使用 DialogFragment 创建一个弹出窗口,在其中我调用视图 PopUpWindow 将显示在屏幕,但是当我尝试通过 id 访问按钮并为它们分配事件处理程序时,例如:

    Button btnCopyText = dp.view.FindViewById<Button>(Resource.Id.btnCopyText);
    btnCopyText.Click += BtnCopyText_Click;

然后我得到一个空引用异常,任何人都可以帮助我,下面是必要的代码。

class dialog_Popup:DialogFragment
{
    public View view;
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        base.OnCreateView(inflater, container, savedInstanceState);
        view = inflater.Inflate(Resource.Layout.PopupWindow, container, false);

        return view;
    }
    public override void OnActivityCreated(Bundle savedInstanceState)
    {
        Dialog.Window.RequestFeature(WindowFeatures.NoTitle);
        base.OnActivityCreated(savedInstanceState);

    }

public class MainActivity : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
     //some code
    }
    public string itemclicked;
    dialog_Popup dp;


    private void Lv_ItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e)
    {
        //View popUpView = LayoutInflater.Inflate(Resource.Layout.PopupWindow,
        //null); // inflating popup layout

        Button height = FindViewById<Button>(Resource.Id.btnCopyText);
        //Then: change the width of the button
        FragmentTransaction transaction = FragmentManager.BeginTransaction();
        dp = new dialog_Popup();
        dp.Show(transaction,"Popup");

        itemclicked = lv.GetItemAtPosition(e.Position).ToString();

        Button btnCopyText = dp.view.FindViewById<Button>(Resource.Id.btnCopyText);
        btnCopyText.Click += BtnCopyText_Click;
        Button btnSaveCurrentAya = dp.view.FindViewById<Button>(Resource.Id.btnSaveCurrentAya);
        btnSaveCurrentAya.Click += BtnSaveCurrentAya_Click;
        Button btnsavingsAya = dp.view.FindViewById<Button>(Resource.Id.savingsAya);
        btnsavingsAya.Click += BtnsavingsAya_Click;*

        Button btnShareFB = dp.view.FindViewById<Button>(Resource.Id.fbShare);
        btnShareFB.Click += BtnShareFB_Click;
    }

}

【问题讨论】:

  • 您的 dialog_Popup 是否有一个 id 为 btnCopyText 的按钮?
  • 是的,dialog_Popup 调用的视图有那个id的按钮

标签: android xamarin view native dialogfragment


【解决方案1】:

FindViewById 发生 NullReferenceException 的原因有多种:

  • 布局不包含 id -> 检查正确的布局和 id 是否被夸大/引用
  • Button 之类的类型不正确

在您的情况下,检查 dp 和 dp.view 是否为空。

这里要提到的一点是,在主视图中引用片段的控件并不是最好的实现。碎片是应该能够独立生活的东西。所以我看到了两种实现你想要的行为的方法:

1) 片段收到一个事件,然后你会听到它。这意味着您的主视图将包含保存某些内容的逻辑。

2) 逻辑移动到片段中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多