I want to use getWindowManager() in my MainActivity, but I don't want to write this method directly in it.
Here is my MainActivity code
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String d= new DisplayMessageActivity().getWeithAndHeight(d);
}
and here is my DisplayMessageActivity code
public class DisplayMessageActivity extends Activity {
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
....
....
setContentView(textView);
}
public String getWeithAndHeight(String url) {
DisplayMetrics dm = new DisplayMetrics();
*getWindowManager().getDefaultDisplay().getMetrics(dm);*
int width = dm.widthPixels;
int height = dm.heightPixels;
String w=new String(""+width);
String h=new String(""+height);
url=url+"&23=w%3A"+w+"%20h%3A"+h+"%20d%3A";
return url;
}
}
my code break at getWindowManager(), please tell me why. Thank you very much.
Way too late to the party here, posting the answer as someone might be able to benefit from it. you can get WindowManager()as a static reference using the context like this.
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
}
now you can use display matrix to get width,height etc
public String getWeithAndHeight(Context context, String url) {
DisplayMetrics dm = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
//....
}
If you are using Kotlin, this code might be helpful to you:
private fun getDeviceWidthAndHeight() {
val metrics = DisplayMetrics()
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager?.defaultDisplay?.getMetrics(metrics)
viewWidth = metrics.widthPixels
viewHeight = metrics.heightPixels
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With