在带有 Xamarin.Android 的广播接收器中使用的 FindViewById 出错

本文关键字:出错 FindViewById 接收器 广播 Xamarin Android | 更新日期: 2023-09-27 17:56:38

我有一个包含 BroadcastReceiver 的活动,如以下代码所示:

public  class MyActivity : Activity
    {
       protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        // Create your application here
        SetContentView(Resource.Layout.activity_myActivity);
        int method = Intent.GetIntExtra(KEY_MYACTIVITY_METHOD, METHOD_MYACTIVITY);
        mAlgo= new algo(this);            
        intent = new Intent(this, typeof( BroadcastService) ); //*****
    }
     [BroadcastReceiver(Enabled = true)]
    [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
    private  class broadcastReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            updateUI(intent);
        }
        private   void updateUI(Intent intent)
        {
            float mx = mAlgo.getmX();
            TextView startx =FindViewById<TextView>(Resource.Id.startx);  //ERROR

        }
    }
}
我有一个错误 FindViewById,

它告诉属性、方法或非静态字段 Activity.FindViewById(int)' 需要对象引用。你能看到出了什么问题吗?谢谢

在带有 Xamarin.Android 的广播接收器中使用的 FindViewById 出错

不能从嵌套类调用FindViewById。您可以:

1) 在嵌套的 broadcastReceiver 类中保存对活动对象的引用:

public class MyActivity : Activity {
    ...
    private class broadCastReceiver : BroadcastReceiver {
        private MyActivity act;
        public broadCastReceiver (MyActivity act) {
            this.act = act;
        }
        private void updateUI (Intent intent) {
            TextView startx = act.FindViewById<TextView> (Resource.Id.startx);
        }
    }
}

2) 或者保留对活动中TextView的引用,并将其传递给广播接收器,类似于第一个示例。