Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use getWindowManager() by another java file

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.

like image 685
劉孟儒 Avatar asked Aug 14 '13 07:08

劉孟儒


3 Answers

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

like image 156
Mightian Avatar answered Sep 18 '22 13:09

Mightian


public String getWeithAndHeight(Context context, String url) {  
    DisplayMetrics dm = new DisplayMetrics();  
    ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
    //....
}   
  • getWindowManager() is a method of Activity class
like image 32
Boris Mocialov Avatar answered Nov 03 '22 12:11

Boris Mocialov


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
    }
like image 8
Nick Avatar answered Nov 03 '22 12:11

Nick