我想从Context或Intent中获取视图或findViewById()?
我正在尝试在我的广播接收器中访问特定视图,onReceive的参数是context和intent。
现在,我有一个类,在其中是我的广播接收器。现在,我正在尝试将广播接收器与其分离,但我需要一种方式来使我仍然可以从我的分离的广播接收器类与我的类上的视图进行通信。
谢谢。
我想从Context或Intent中获取视图或findViewById()?
我正在尝试在我的广播接收器中访问特定视图,onReceive的参数是context和intent。
现在,我有一个类,在其中是我的广播接收器。现在,我正在尝试将广播接收器与其分离,但我需要一种方式来使我仍然可以从我的分离的广播接收器类与我的类上的视图进行通信。
谢谢。
TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);
从上下文开始,可以通过以下方式获取相关活动的根视图:
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);
View v = rootView.findViewById(R.id.your_view_id);
强制类型转换为 View v = (View) rootView.findViewById(R.id.your_view_id);
,而且 View 类可以是任何派生自 View 的子类。 - Joaquin Iurchuk在您的广播接收器中,您可以通过从XML资源中填充根布局来访问视图,然后使用findViewByid()从该根布局中找到所有视图:
View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);
myImage = (ImageView) view.findViewById(R.id.my_image);
setContentView()
进行了填充。但是,如果您省略对setContentView()
的调用,并在手动填充后手动附加它,则可能会没问题(我忘记了如何做到这一点,但手动视图附加可以在任何Activity
或Fragment
中完成)。 - samus首先使用这个:
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);
ClassicSingleton
将持有对Activity的引用。 - Dmitry Zaytsev