FindViewById在非活动类中

时间:2017-01-12 22:20:34

标签: java android

如何在非活动类中使用findViewById()。以下是我的代码段。我收到错误消息:"无法解析方法findViewById"如果直接使用。如果我尝试使用类构造函数(其中imageView可用)我得到此错误"无法解析符号上下文"

public class MyBroadcastReceiver extends FirstBroadcastReceiver {

Activity activity;
public MyBroadcastReceiver(Context context, Activity activity){
    this.context=context;     // error here(cannot resolve symbol context)
    this.activity=activity;
}

    @Override
    protected void (Context context) {
    // content
    }

    @Override
    public void onButton(Context context, boolean isClick) {

        if(isClick) {

    ImageView blueImage = (ImageView)activity.findViewById(R.id.imageView);
    blueImage.setColorFilter(0xff000000);
         }
    }
.......
....
    // and so on

下面是MyBroadcastReceiver类实例的MainActivity。它是否正确?

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     // and so on
    }
}


MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver(MainActivity.this,this);

 @Override
 public void onActivityResult() {
  // some code
  }

@Override
     public void onInitialized(MyManager manager){
 // some code   
 }

3 个答案:

答案 0 :(得分:0)

BroacastReceiver完全在后台运行,侦听操作系统或其他应用程序发送的Intents。它不对任何UI交互负责,也不能访问任何视图。因此,findViewById不能在BroadcastReceiver中使用。

另见 - What is BroadcastReceiver and when we use it?

答案 1 :(得分:0)

在使用findViewByid之前,您必须将View传递给非活动类 和 尝试使用

view.findViewByid(R.id.view_id);

答案 2 :(得分:0)

因为context类中的nullBroadcast。使用Broadcast类构造函数在parent_activity(Where the imageView is available)中传递Broadcast上下文来访问上下文:

public class Broadcast extends BroadCastReceiver {

Activity activity;
public Broadcast(Context context,Activity activity){
this.context=context;
this.activity=activity;
}
 .......
    ....... //so on

并在parent_activity创建Broadcast类实例,方法是将parent_activity上下文传递为:

Broadcast broadcast = new Broadcast(parent_activity.this,this);

activity实例用作:

@Override
public void onButton(Context context, boolean isClick) {

    if(isClick) {
       ImageView blueImage = (ImageView) activity.findViewById(R.id.imageView);  //<--- here
     }
}
 .........
      ......... //so on