android获取屏幕大小非常常用,例如写个程序,如果要做成通用性很强的程序,适用屏幕很强,一般布局的时候都是根据屏幕的长宽来定义的,所以我把这个总结一下,方便日后忘记的时候查阅。还有就是有时候写程序根据需求不需要title,可以在程序中设置无title的屏幕!转载请标明出处:
http://blog.csdn.net/wdaming1986/article/details/6769821
程序的效果图:
代码说明一切真理:
一、mainActivity。java类得代码:
Java代码
class="dp-j" start="1">
- package com.cn.daming;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.DisplayMetrics;
- import android.view.Window;
- import android.view.WindowManager;
- import android.widget.TextView;
-
- public class MainActivity extends Activity {
-
- private TextView mTextView;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- requestWindowFeature(Window.FEATURE_NO_TITLE);
-
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);
- setContentView(R.layout.main);
-
- DisplayMetrics dm = new DisplayMetrics();
-
- getWindowManager().getDefaultDisplay().getMetrics(dm);
-
- int screenWidth = dm.widthPixels;
-
- int screenHeight = dm.heightPixels;
-
- mTextView = (TextView)findViewById(R.id.text_view);
- mTextView.setText("屏幕宽度: "+screenWidth+
- "\n屏幕高度: "+screenHeight);
- }
- }
二、main.xml布局文件的代码:
Html代码
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/text_view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_gravity="center_vertical|center_horizontal"
- android:gravity="center"
- android:text="@string/hello"
- android:textSize="18pt"
- />
- </LinearLayout>