Android Helper classes

10,351

Solution 1

the first is how to pass the context into the java class

You can pass it as parameter of each method. Also for easier access you can make those methods as final static.

how to use methods that extend from activity in the helper class, below is my helper class.

This sounds like bad design of application logic. Methods inherited from Activity class should be visible and used only from Activity subclass(es).

But if you really need it, also you can pass Activity as method parameter but i recommend you to find another way.

Update:

how do I pass the context as a marameter of each method?

Example of method:

public static final void foo(Context c, int value, String message) {
   // do your stuff
}

Solution 2

Why not use abstract BaseActivity with all these methods? And extend this class in all your other Activities?

Share:
10,351

Related videos on Youtube

Paddy1990
Author by

Paddy1990

Updated on June 26, 2022

Comments

  • Paddy1990
    Paddy1990 almost 2 years

    I have a couple of methods in my android application that I would like to reuse across multiple Activities, as it's a Java helper class I'm not extending from anything. I have two problems, the first is how to pass the context into the java class and the second is how to use methods that extend from activity in the helper class, below is my helper class:

    Java Class

    public class ScreenHelper {
        Context context;
        public ScreenHelper(Context ctx) {
            this.context = ctx;
        }
    
        public int getStatusBarHeight(layout layout) {
            Rect r = new Rect();
            Window w = (Window) getWindow();
            w.getDecorView().getWindowVisibleDisplayFrame(r);
            return r.top;
        }
    
        public int getScreenHeight() {
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int ScreenHeight = metrics.heightPixels;
            return ScreenHeight;
        }
    
        public int getTitleBarHeight() {
            RelativeLayout relaLayout = (RelativeLayout) findViewById(R.id.title_bar);
            int titleHeight = relaLayout.getHeight();
    
            Log.d("Title Height","Title Height:" + titleHeight);
            return titleHeight;
        }
    }
    

    Any help would be much appreciated.

  • Paddy1990
    Paddy1990 almost 10 years
    So how would I go about doing that? Plus, if the classes I want to use this code on already extends from another class, how how would I do this? thanks
  • Paddy1990
    Paddy1990 almost 10 years
    Well the classes I need to use this code with extend my menuActivity, which extends SherlockActivity, is this not a good design? how would I go about doing it differently? So how do I pass the context as a marameter of each method? code examples would be very helpful

Related