How do you get a view reference from a class that doesn't extend Activity?
I want to have a class "Utils", that will have several methods used all over my code. For example, I have a top bar with a textview
and two ImageButton
s that must display different texts and icons on different activities.
I find myself writing stuff like this on every activity:
(TextView) topBarText = (TextView) findViewById(R.id.topBarText);
topBarText.setText(R.id.mytextForThisView);
I'd like to findViewById once in my wh开发者_开发技巧ole app, and call a method setupTopBar(String text, R.id.iconForImageButton1, R.id.iconForImageButton2)
, or even pass the current Activity's id and let the method figure out what to show in the text and images.
I created the class Util
, but it doesn't extend Activity
. The problem is that if it doesn't, findViewById
isn't accessible, so I can't use it.
What's the pattern to do something like this in Android?
Your helper methods should look like
public static void setTopBarText(Activity act, int textId){
(TextView) topBarText = (TextView)act.findViewById(R.id.topBarText);
topBarText.setText(textId);
}
Then you can do a static import from Activity and call
setTopBarText(this, R.id.mytextForThisView);
The Answer is not good for some situation.
This is my method:
In your Activity:
YouCustomClassObject.passView((View)findViewById(R.id.aview));
Using parameter passing can solve this kind of problem.
精彩评论