【问题标题】:Error with FindViewById used in a Broadcast receiver with Xamarin.Android在 Xamarin.Android 的广播接收器中使用 FindViewById 时出错
【发布时间】:2018-05-15 10:10:21
【问题描述】:

我有一个包含 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)' 需要对象引用。你能看出出了什么问题吗?谢谢

【问题讨论】:

    标签: c# xamarin.android findviewbyid


    【解决方案1】:

    您不能从嵌套类调用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 的引用,并将其传递给广播接收器,类似于第一个示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多