I have an activity which has a static method for updating a textfield
. This way I can update this view from another activity.
But now I'm trying to get a Context variable in this static method which is not possible. I've tried declaring a Context variable and initialising it in onCreate ( context = 开发者_StackOverflowgetApplicationContext();)
But still I can't access context in this static method. How is this normally done?
edit: a little bit more information about my situation. I'm starting a countdowntimer
in an activity(a) which updates another activity's(b) ``textfield every second. And it does this by accessing b's setTextField
in a static way..
How is this normally done?
Accessing a TextView
via a static method is not the best way to update the field from another activity. If you want to pass a value to the activity when it starts, you can send data via the intent (i.e. intent.getExtras
). If you want to pass data back from a sub-activity, you can use startActivityForResult
.
The way you are going is very strange. Why are you trying to change one activity content from another? May be you need to use startActivityForResult
to strat a new activity and then return result from it and change views depending on it?
You might want to check some documentation on OO and using static functions. It is not considered a very good approach.
But as we are not talking about a better complete sollution: you can add a parameter with a context to the function, and just give it when you call the function :)
I would suggest the LocalBinder pattern to update the other Activity: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html
Can you do something like this?
something like this <viewobj>.getContext()
Ref: How can I start an Activity from a non-Activity class?
Whenever you're busy with Activity A, there's no point in updating something on Activity B as it is simply not shown to the user at that point in time.
Seems to me you need to have some kind of global variable here that can be picked up in the onResume of Activity B.
Checkout this question : How to declare global variables in Android?
It shows you how to use the Application class to maintain global application state, accessable from all activities when needed.
精彩评论