Android 橫豎屏檢測代碼

jopen 10年前發布 | 17K 次閱讀 Android Android開發 移動開發

package com.example;

import android.app.Activity; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast;

public class ChangeConfiguationActivity extends Activity {

@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.configuration_layout); Button btn = (Button) findViewById(R.id.bn); btn.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) { Configuration config = getResources().getConfiguration(); // 如果是橫屏則設為豎屏 if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { ChangeConfiguationActivity.this .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { ChangeConfiguationActivity.this .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } }); }

@Override public void onConfigurationChanged(Configuration newConfig) {

super.onConfigurationChanged(newConfig);

String screen = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? "橫向屏幕" : "豎向屏幕"; Toast.makeText(ChangeConfiguationActivity.this, "系統屏幕方向發生了變化:" + screen, Toast.LENGTH_LONG).show(); }

}</pre>

 

AndroidManifest.xml 配置

 

<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />

android:configChanges="orientation"
 <activity
            android:name=".XXX"
            android:configChanges="orientation"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!