views:

23

answers:

1

Hi,

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 ImageButtons 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 whole app, and call a method setupTopBar(String text, R.id.iconForImageButton1, R.id.iconForImageButton2), or even pass "this 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 there, can't find stuff etc.

What's the pattern to do something like this in Android?

Thanks llappall

+1  A: 

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);
alex