【问题标题】:Unhandled exception in this simple Xamarin Android program这个简单的 Xamarin Android 程序中未处理的异常
【发布时间】:2017-06-10 22:42:26
【问题描述】:

我正在 Visual Studio 2017 中使用我的第一个 Android Xamarin 程序进行测试,并添加了一个文本视图,并切换到主视图。它构建得很好,但是当我单击开关时,我得到一个未处理的异常,它没有提供其他细节。为什么抛出异常,它是什么,我做错了什么?

using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;

namespace TestAndroidApp
{
    [Activity(Label = "TestAndroidApp", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
        }

        public void setActivatedLabel(View v)
        {
            var sw = (Switch)Resource.Id.switchActivate;
            ((TextView)Resource.Id.textActivated).Text = sw.Checked ? "On" : "Off";    
        }
    }
}

【问题讨论】:

    标签: android xamarin xamarin.android


    【解决方案1】:

    您需要使用FindViewById通过资源标识符来检索对象:

    var sw = FindViewById<Switch>(Resource.Id.switchActivate);
    var textView = FindViewById<TextView>(Resource.Id.textActivated);
    textView.Text = sw.Checked ? "On" : "Off";  
    

    在这种情况下,sw 现在将是 Switch 对象,该对象由您的布局文件中的 switchActivate id 引用,该文件由 SetContentView 方法加载/扩展。

    【讨论】:

    • 辛苦了!我还在onCreate 中为checkedChanged 添加了一个事件处理程序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多