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