본문 바로가기

소프트웨어/안드로이드

화면 사이즈 확인 테스트 코드

Java

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main_java);
    init();
}

private void init() {
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics outMetrics = new DisplayMetrics();
    display.getMetrics(outMetrics);

    float density = getResources().getDisplayMetrics().density;
    float dpHeight = outMetrics.heightPixels / density;
    float dpWidth = outMetrics.widthPixels / density;

    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    float dpHeight2 = displayMetrics.heightPixels / displayMetrics.density;
    float dpWidth2 = displayMetrics.widthPixels / displayMetrics.density;

    TextView result = findViewById(R.id.tv_result);

    StringBuilder builder = new StringBuilder();
    builder.append("density: ").append(density).append("\n\n");
    builder.append("dpHeight: ").append(dpHeight).append("\n");
    builder.append("dpWidth: ").append(dpWidth).append("\n\n");
    builder.append("dpHeight2: ").append(dpHeight2).append("\n");
    builder.append("dpWidth2: ").append(dpWidth2).append("\n\n");
    builder.append("DPI: ").append(getResources().getDisplayMetrics().densityDpi);

    result.setText(builder);
}

 

Kotlin

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    init()
}

fun init() {
    val display = windowManager.defaultDisplay
    val outMetrics = DisplayMetrics()
    display.getMetrics(outMetrics)

    val density = resources.displayMetrics.density
    val dpHeight = outMetrics.heightPixels / density
    val dpWidth = outMetrics.widthPixels / density

    val displayMetrics = resources.displayMetrics
    val dpHeight2 = displayMetrics.heightPixels / displayMetrics.density
    val dpWidth2 = displayMetrics.widthPixels / displayMetrics.density

    val result = findViewById<TextView>(R.id.tv_result)

    val builder = StringBuilder()
    builder.append("density: ").append(density).append("\n\n")
    builder.append("dpHeight: ").append(dpHeight).append("\n")
    builder.append("dpWidth: ").append(dpWidth).append("\n\n")
    builder.append("dpHeight2: ").append(dpHeight2).append("\n")
    builder.append("dpWidth2: ").append(dpWidth2).append("\n\n")
    builder.append("DPI: ").append(resources.displayMetrics.densityDpi)

    result.text = builder

    findViewById<View>(R.id.btn_switch).setOnClickListener {
        val i = Intent(this, MainActivityInJava::class.java)
        startActivity(i)
    }
}