android获取手机屏幕分辨率

本文主要解决获取手机屏幕的大小:例子很简单,主要通过 DisplayMetrics 类来获取相关的信息,代码如下 
 

效果图:

android获取手机屏幕分辨率_第1张图片                         

XML文件

1.   activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.displaymetricsdemo.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/display_metrics_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/display_metrics"
         />
    
    <Button
        android:id="@+id/metrics_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/display_metrics_tv"
        android:text="@string/metrics"
        />

</RelativeLayout>

2.strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">DisplayMetricsDemo</string>
    <string name="display_metrics">显示屏幕分辨率:</string>
    <string name="action_settings">Settings</string>
    <string name="metrics">获取屏幕分辨率</string>

</resources>

3.MainActivity.java

private TextView displayMetricsTv;
	private Button metricsBtn;
	private DisplayMetrics displayMetrics;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        displayMetricsTv = (TextView) this.findViewById(R.id.display_metrics_tv);
        metricsBtn = (Button) this.findViewById(R.id.metrics_btn);
        
        metricsBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				displayMetrics = new DisplayMetrics();
				getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
				
				displayMetricsTv.setText("显示屏幕分辨率:\r\n" + displayMetrics.widthPixels + " * " + displayMetrics.heightPixels);
				
				
			}
        });
    }




你可能感兴趣的:(android,button,分辨率,displaymetrics)