Change Screen Direction

Because changing screen direction is belong to change system setting,we should modify 'mainfest' file,add the following line :

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

In addition that,we also should set screen primary direction. Adding a attribution android:screenOrientation="portrait" in the Activity that is existed to 'mainfest' file.


A called onConfigurationChanged event is triggered while changing screen direction,so we should add a attribution

android:configChanges="orientation|keyboard"  in the same Activity.


Then the main code as follows

public class ChgScreenActivity extends Activity {
    private Button but = null;
    private ImageView img = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        but = (Button)super.findViewById(R.id.chg);
        img = (ImageView)super.findViewById(R.id.img);
        but.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(ChgScreenActivity.this.getRequestedOrientation()
                        == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED){
                    but.setText("錯誤,無法改變屏幕的方向");
                }else if(ChgScreenActivity.this.getRequestedOrientation()
                        == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ){
                    ChgScreenActivity.this.setRequestedOrientation(
                            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    //img.setImageResource(R.drawable.v);
                }else if(ChgScreenActivity.this.getRequestedOrientation()
                        == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
                    ChgScreenActivity.this.setRequestedOrientation(
                            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    //img.setImageResource(R.drawable.h);
                }
            }
        });
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
        if(newConfig.orientation ==
            Configuration.ORIENTATION_LANDSCAPE){
            but.setText("改變屏幕方向爲豎屏(當前爲橫屏)");
            img.setImageResource(R.drawable.v);
        }else if(newConfig.orientation ==
            Configuration.ORIENTATION_PORTRAIT){
            but.setText("改變屏幕方向爲橫屏(當前爲豎屏)");
            img.setImageResource(R.drawable.h);
        }
        
        
    }
   
}


changing image while chaning screen direction,the function is needed to realize in the above event

發佈了32 篇原創文章 · 獲贊 6 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章