Java & Android
[Android] Display Size Check
우동우동우
2013. 11. 13. 16:45
안드로이드 Display Size를 구하는 방법에 대해 정리를 한번 해 보았다.
package com.minz.tabsize; import java.lang.reflect.Method; import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import android.widget.TextView; public class DisplaySizeCheckActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView)findViewById(R.id.TextView); WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); float width = -1; float height = -1; /** * 3.0 이상에서 NaviBar가 사라지지 않아 정확한 치수를 알수 없다. * 때문에 API 상에서 나타나지는 않으나 실제로 존재하는 getRawWidth(), * getRawHeight() 함수를 불러본다. */ try { Method mGetRawW = Display.class.getMethod("getRawWidth"); Method mGetRawH = Display.class.getMethod("getRawHeight"); width = (Integer)mGetRawW.invoke(display); height = (Integer)mGetRawH.invoke(display); } catch (Exception e) { } // 위 코드에서 에러가 난 경우 기존에 치수를 가져오는 방법을 사용 if(width < 0){ width = metrics.widthPixels; } if(height < 0){ height = metrics.heightPixels; } // px -> dp로 변환 float hdp = height / (metrics.densityDpi / 160f); float wdp = width / (metrics.densityDpi / 160f); // 표시 tv.setText("width px = " + width + ", height px = " + height); tv.append("\nwidth dp = " + wdp + ", height dp = " + hdp); // 스크린 사이즈 가져오기. String size = "not_known"; int screenSizeType = (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK); if(screenSizeType == Configuration.SCREENLAYOUT_SIZE_XLARGE) { size = "xlarge"; } else if(screenSizeType == Configuration.SCREENLAYOUT_SIZE_LARGE) { size = "large"; } else if(screenSizeType == Configuration.SCREENLAYOUT_SIZE_NORMAL ) { size = "normal"; } else if(screenSizeType == Configuration.SCREENLAYOUT_SIZE_SMALL){ size = "small"; } tv.append("\nscrean size buckets = " + size); } }