App/Activity/Screen Orientation

测试android屏幕方向的小Demo

1、首先我们在values下面新建文件arrays.xml(用来在下拉列表中显示)

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <!-- Used in app/Screen Orientation -->
    <string-array name="screen_orientations"
        <item>UNSPECIFIED</item>
        <item>LANDSCAPE</item>
        <item>PORTRAIT</item>
        <item>USER</item>
        <item>BEHIND</item>
        <item>SENSOR</item>
        <item>NOSENSOR</item>
        <item>SENSOR_LANDSCAPE</item>
        <item>SENSOR_PORTRAIT</item>
        <item>REVERSE_LANDSCAPE</item>
        <item>REVERSE_PORTRAIT</item>
        <item>FULL_SENSOR</item>
    </string-array>
</resources>

 2、我们在代码中定义相对应数组

 final static int mOrientationValues[] = new int[] {
        ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED,
        ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
        ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
        ActivityInfo.SCREEN_ORIENTATION_USER,
        ActivityInfo.SCREEN_ORIENTATION_BEHIND,
        ActivityInfo.SCREEN_ORIENTATION_SENSOR,
        ActivityInfo.SCREEN_ORIENTATION_NOSENSOR,
        ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
        ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT,
        ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
        ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
        ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR,
    };

 3、处理用户选择

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_activity_screen_orientation);
        
        mOrientation = (Spinner)findViewById(R.id.app_activity_screen_orientation);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.screen_orientations, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mOrientation.setAdapter(adapter);
        mOrientation.setOnItemSelectedListener(
                new OnItemSelectedListener() {
                    public void onItemSelected(
                            AdapterView<?> parent, View view, int position, long id) {
                        setRequestedOrientation(mOrientationValues[position]);
                    }

                    public void onNothingSelected(AdapterView<?> parent) {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                    }
                });
    }

 

posted @ 2014-10-22 20:39  Michelle's Home  阅读(498)  评论(0编辑  收藏  举报