Search code examples
androidstatic-methodsfindviewbyid

findViewById in static method in different class


Inside on of my android fragments I have the following simple check as to whether my app runs on a tablet or not (on a tablet I have 3 views open, view 2 and 3 are not seen on a phone, only the first one is seen)

boolean mDualPane;
View detailsFrame = getActivity().findViewById(R.id.content1);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

This works fine in the fragment itself, but I need the exact same check in many fragments and so I wanted to have it in my "MiscMethods" class that I use for frequently used methods in multiple classes. Now the same cod in my class looks like this:

public class MiscMethods{    
public static boolean landscapeChecker(){
    boolean mDualPane;
    View detailsFrame = getActivity().findViewById(R.id.content1);
    mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
    return mDualPane;   
}
}

getActivity (and if I delete that findViewById) is undefined for the type MiscMethods.

Now I have an Application class for context like here

public static void ErrorToast(int errorCode) {
    String errorString = null;
    switch (errorCode) {
    case 1:
        errorString = App.getContext().getString(R.string.error_tooManyFieldsEmpty);
        break;
    case 2:
        errorString = App.getContext().getString(R.string.error_featureComingSoon);
        break;
    case 3:
        errorString = App.getContext().getString(R.string.error_SwitchBreak);
        break;
    default:
        errorString="Wrong Error Code";
        break;
    }
    Toast errormsg = Toast.makeText(App.getContext(), errorString, Toast.LENGTH_SHORT);
    errormsg.setGravity(Gravity.CENTER, 0, 0);
    errormsg.show();
}

but this App.getContext() also does not help.

How can I fix this?


Solution

  • It looks like you're searching for a quick-and-dirty solution, so here are two:

    • Change the method signature's to take the activity as a parameter:

      public static boolean landscapeChecker(Activity activity).

      In the method, use the passed-in activity in place of getActivity(). Call it from your various activities like boolean mDualPane = landscapeChecker(this).

    • Subclass Activity and put the method there instead. For this solution, you would create a class MyActivity extends Activity, then make your various activities extend MyActivity instead of extend Activity. In the method, use this in place of getActivity().