如何从上下文获取视图?

我想从上下文获取视图或findViewById()? 还是从意图?

我试图达到在我的广播接收器的具体视图和onReceive的参数是上下文和意图。

那么,我有一个class,其中是我的广播接收器。 现在,我正试图将广播接收器与它分开,但是我需要一种方法,以便从分离的广播接收器类中继续与我的课堂上的视图进行通信。

谢谢。

从上下文开始,关联活动的根视图可以由

View rootView = ((Activity)_context).Window.DecorView.FindViewById(Android.Resource.Id.Content); 

在原始Android中,它看起来像这样:

 View rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content) 

然后简单地调用这个findViewById

 View v = rootView.findViewById(R.id.your_view_id); 

例如,你可以find任何的textView:

 TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1); 

在你的广播接收器中,你可以通过膨胀的方式从XML资源的根布局访问一个视图,然后用findViewByid()从这个根布局查找所有视图:

 View view = View.inflate(context, R.layout.ROOT_LAYOUT, null); 

现在,您可以通过“视图”访问您的视图,并将其转换为您的视图types:

 myImage = (ImageView) view.findViewById(R.id.my_image); 

首先使用这个:

 LayoutInflater inflater = (LayoutInflater) Read_file.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); Read file is current activity in which you want your context. View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id)); 

那么你可以使用它来查找布局中的任何元素。

 ImageView myImage = (ImageView) layout.findViewById(R.id.my_image); 

你为什么不使用单身?

 import android.content.Context; public class ClassicSingleton { private Context c=null; private static ClassicSingleton instance = null; protected ClassicSingleton() { // Exists only to defeat instantiation. } public void setContext(Context ctx) { c=ctx; } public Context getContext() { return c; } public static ClassicSingleton getInstance() { if(instance == null) { instance = new ClassicSingleton(); } return instance; } } 

然后在活动课上:

  private ClassicSingleton cs = ClassicSingleton.getInstance(); 

而在非活动课上:

 ClassicSingleton cs= ClassicSingleton.getInstance(); Context c=cs.getContext(); ImageView imageView = (ImageView) ((Activity)c).findViewById(R.id.imageView1);