thefriend
thefriend

Reputation: 339

Get Screen width and height on android 2.2

How I can get screen width and height for use this value on device with android version 2.2(API lv8). I use this code:

public static Point Maximum(Context context)
       {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int width = display.getWidth();  // deprecated
            int height = display.getHeight();  // deprecated
            Point temp=new Point();     
            return temp;
       }

And when i want check by print Max point to textview:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView txt= (TextView)findViewById(R.id.text1);
    txt.setText(Math.Maximum(this).toString()); 
}

Point is (0,0). What problem?

Upvotes: 0

Views: 242

Answers (4)

Mukesh Rana
Mukesh Rana

Reputation: 4091

Try this for getting your screen width. Similarly you can get screen height or can customize the same for returning both in a single function.

 @SuppressWarnings("deprecation")
 @SuppressLint("NewApi")
 private int getScreenWidth() {
    int width = 400;
    int height = 600; // just intialising it to default value in case if there is any problem getting screen width
    WindowManager wm = (WindowManager) activity // activity is the context if you are using this method in adapter. Otherwise in Activity you can simply ignore this
            .getSystemService(Context.WINDOW_SERVICE); 
    Display display = wm.getDefaultDisplay();
    if (android.os.Build.VERSION.SDK_INT >= 13) {
        Point size = new Point();
        display.getSize(size);
        width = size.x;
        height = size.y;
    } else {
        width = display.getWidth();
        height= display.getHeight();
    }
    return width;//or height
}

Upvotes: 0

Sakthivel Appavu
Sakthivel Appavu

Reputation: 575

Get Device Width and Height, return as point. Hope u like this.

public static Point Maximum(){
    Display display = activity.getWindowManager().getDefaultDisplay();
    int width  = display.getWidth();
    int height = display.getHeight();
    Point temp=new Point();
    temp.set(width, height);     
    return temp;
}

Upvotes: 0

Tushski
Tushski

Reputation: 242

Try this code. But this API is deprecated in the new SDK versions you can use this.

Display display = activity.getWindowManager().getDefaultDisplay();
int width  = display.getWidth();
int height = display.getHeight();

Upvotes: 1

arielhad
arielhad

Reputation: 2153

Try this code:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;

Upvotes: 0

Related Questions