Android实现动态切换横竖屏,保存横竖屏数据(用Preference存储)

来源:互联网 发布:淘宝店释放是什么意思 编辑:程序博客网 时间:2024/05/16 19:11
package com.test;import android.app.Activity;import android.content.pm.ActivityInfo;import android.os.Bundle;import android.view.View;import android.view.View.OnLongClickListener;import android.view.Window;import android.view.WindowManager;import android.widget.TextView;import android.widget.Toast;/** * class name:TestAndroid_BasicActivity<BR> * class description:动态设置横竖屏哦<BR> * PS:既然要实现横竖屏的变更,所以设置的记录就必须持久化存储 你可以用数据库,这里用的是简单一点的Preference <BR> *  * @version 1.00 2011/09/21 * @author CODYY)peijiangping */public class TestAndroid_BasicActivity extends Activity implementsOnLongClickListener {// 设置默认为横屏SCREEN_ORIENTATION_LANDSCAPE,竖屏SCREEN_ORIENTATION_PORTRAITprivate int ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;private TextView textview;private MyPreference mpf;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mpf = new MyPreference(this, "love");try {ORIENTATION = mpf.read("model");} catch (Exception e) {System.out.println("first");}requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏// 设置横竖屏setRequestedOrientation(ORIENTATION);setContentView(R.layout.main);init();}private void init() {textview = (TextView) this.findViewById(R.id.textview);textview.setText("Loveing");textview.setOnLongClickListener(this);// 实现长按事件监听}@Overridepublic boolean onLongClick(View v) {// 如果当前为横屏if (ORIENTATION == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {// 将竖屏保存进MyPreferencempf.write("model", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 显示一个toast提示Toast toast = Toast.makeText(this, "横屏已经切换成竖屏,请重新进入应用查看",Toast.LENGTH_SHORT);toast.show();// 如果当前为竖屏} else if (ORIENTATION == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {// 将横屏保存进MyPreferencempf.write("model", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 显示一个toast提示Toast toast = Toast.makeText(this, "竖屏已经切换成横屏,请重新进入应用查看",Toast.LENGTH_SHORT);toast.show();}return false;}}

package com.test;import android.content.Context;import android.content.SharedPreferences;import android.content.pm.ActivityInfo;public class MyPreference {private SharedPreferences preference;private String file_name;private int value_int;//设置默认为横屏private int defultint = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;;public MyPreference(Context context, String str) {file_name = str;value_int = 0;preference = context.getSharedPreferences(file_name, 0);}public int read(String name) {value_int = preference.getInt(name, defultint);return value_int;}public void write(String name, int value) {SharedPreferences.Editor editor = preference.edit();editor.putInt(name, value);editor.commit();}}