Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - How to get view from context?

I want to get the view or findViewById() from Context? Or from intent?

I'm trying to reach a specific view in my broadcast receiver and the parameter of onReceive are context and intent.

Well, I have a class and within it is my broadcast receiver. Now, I'm trying to separate the broadcast receiver from it, but I need a way so I can still communicate with the views on my class from my separated broadcast receiver class.

Thanks.

like image 267
lorraine Avatar asked Oct 29 '12 01:10

lorraine


3 Answers

For example you can find any textView:

TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);
like image 140
KuzyaTheBrownie Avatar answered Nov 18 '22 14:11

KuzyaTheBrownie


Starting with a context, the root view of the associated activity can be had by

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

In Raw Android it'd look something like:

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

Then simply call the findViewById on this

View v = rootView.findViewById(R.id.your_view_id);
like image 29
samus Avatar answered Nov 18 '22 14:11

samus


In your broadcast receiver you could access a view via inflation a root layout from XML resource and then find all your views from this root layout with findViewByid():

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

Now you can access your views via 'view' and cast them to your view type:

myImage = (ImageView) view.findViewById(R.id.my_image);
like image 7
Marcin S. Avatar answered Nov 18 '22 13:11

Marcin S.