在 Xamarin.Android 的广播接收器中使用 FindViewById 时出错
Error with FindViewById used in a Broadcast receiver with Xamarin.Android
我有一个 activity,里面有一个 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)' 需要对象引用。你能看出哪里出了问题吗?谢谢
您不能从嵌套的 class 调用 FindViewById
。你可以:
1) 在嵌套的 broadcastReceiver
class:
中持有对 activity 对象的引用
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) 或者在 activity 中保存对 TextView
的引用,并像第一个示例一样将其传递给广播接收器。
我有一个 activity,里面有一个 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)' 需要对象引用。你能看出哪里出了问题吗?谢谢
您不能从嵌套的 class 调用 FindViewById
。你可以:
1) 在嵌套的 broadcastReceiver
class:
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) 或者在 activity 中保存对 TextView
的引用,并像第一个示例一样将其传递给广播接收器。