1

For some reason, I have to obtain screen dimension in a non-activity extending class. I try to use below method:

DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int w = metrics.widthPixels;

so I can use "w" as the width dimension in pixels. However, it seems this method is only for class which extended activity. Any solution?

Thanks all.

Kit Ng
  • 993
  • 4
  • 12
  • 24

2 Answers2

1

You have to pass in a context through the constructor of the class:

public class Something {

    Context context;

    public Something(Context context){
        this.context = context;
    }

    public int getDisplayWidth(){
        DisplayMetrics metrics = this.context.getResources().getDisplayMetrics();
        int w = metrics.widthPixels;
        return w;
    }
}
Ahmad
  • 69,608
  • 17
  • 111
  • 137
0

In order to access Activity methods without needing to pass context every time you need it, it's useful to keep a reference to the currentActivity in your application object.-

public class YourApplication extends Application {
    public YourApplication() {
        instance = this;        
    }

    public static YourApplication getInstance() {
        return instance;
    }

    public Activity getCurrentActivity() {
        return currentActivity;
    }

    public void setCurrentActivity(Activity currentActivity) {
        this.currentActivity = currentActivity;
    }
}

In your AndroidManifest.xml

<application
    android:name=".YourApplication"
    ...
    >
</application>

And in your Activities onResume method.-

@Override
protected void onResume() {
    super.onResume();

    YourApplication.getInstance().setCurrentActivity(this);
}

Also, I usually have a ParentActivity to be extended by the rest of my activities, grouping some common logic like this one.

ssantos
  • 16,001
  • 7
  • 50
  • 70