屏幕橫豎屏切換時,Activity不重複執行oncreate

需要在AndroidManifest.xml增加代碼:

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

<activity
            android:name="HelloWorldActivity"
            android:label="@string/title_name" 
            android:configChanges="orientation|keyboard|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


然後在Activity的子類下重寫(import android.content.res.Configuration; ----->導入import快捷:CTRL+SHIFT+O):

@Override  
    public void onConfigurationChanged(Configuration newConfig) {  
        super.onConfigurationChanged(newConfig);  
        try {  
            if(this.getResources().getConfiguration().orientation == newConfig.ORIENTATION_LANDSCAPE){  
                Log.v("orientation", "ORIENTATION_LANDSCAPE");  
                Toast.makeText(getApplication(), "ORIENTATION_LANDSCAPE(橫屏)", Toast.LENGTH_LONG).show();
            } else if(this.getResources().getConfiguration().orientation == newConfig.ORIENTATION_PORTRAIT){
            Log.v("orientation", "ORIENTATION_PORTRAIT");  
            Toast.makeText(getApplication(), "ORIENTATION_PORTRAIT(豎屏)", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章