Android获取屏幕方向及键盘状态的小例子,android 获取屏幕方向
- 格式:docx
- 大小:12.53 KB
- 文档页数:1
Android 手机有个比较有趣的功能,就是当你把手机横过来的时候,手机的内容也会跟着横过来。
那么要如何通过程序控制Activity 的显示方向呢?在MonoDroid 里,若要通过程序改变屏幕显示的方向,只要调用SetRequestedOrientation 方法即可,而若要取得当前屏幕的方向,则使用RequestedOrientation 属性即可。
本范例很简单,界面只有一个按钮,点击它的时候判断当前屏幕方向,如果是竖屏(Portrait ),则将其改为横屏(Landscape ),反之亦然。
布局文件如下: + expand source?01 02 03 04 05 06 07 08 09 10 <?xml version="1.0"encoding="utf-8"?><RelativeLayoutxmlns:android="/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"><Button android:id="@+id/btnLandScape"android:text="按我旋转屏幕"android:layout_width="wrap_content"android:layout_height="wrap_content"/></RelativeLayout>程序也很简单,只要在Button 的单击事件中判断当前的屏幕方向,然后调用SetRequestedOrientation 方法: + expand source?01 02 03 04 05 06 07 08 09 protectedoverridevoidOnCreate(Bundle bundle){base.OnCreate(bundle);SetContentView(yout.Main);Button btnLandScape = FindViewById<Button>(Resource.Id.btnLandScape); btnLandScape.Click += (sender, e) =>{if(this.RequestedOrientation ==(int)ndscape){this.SetRequestedOrientation(Android.Content.PM.ScreenOrientation.P ortrait);Toast.MakeText(this, "旋转为竖屏", ToastLength.Long).Show(); }elseif(this.RequestedOrientation ==(int)Android.Content.PM.ScreenOrientation.Portrait){this.SetRequestedOrientation(Android.Content.PM.ScreenOrientation.L10 11 1213141516171819andscape);Toast.MakeText(this, "旋转为横屏", ToastLength.Long).Show(); }};}在模拟器里运行程序,点击按钮,咦?怎么没有反应?跟踪了一下代码一看,发现this.RequestedOrientation 竟然是-1!,这是怎么回事儿呢?原来,在Android 里,如果我们不在AndroidManifest.xml 当中设置Activity 的android:screenOrientation 属性,否则即使程序运行时屏幕是竖屏的,this.RequestedOrientation 也默认为-1。
一、禁止横竖屏转换Android横竖屏切换在手机开发中比较常见,很多软件在开发过程中为了避免横竖屏切换时引发不必要的麻烦,通常禁止掉横竖屏的切换,通过在AndroidManifest.xml中设置activity中的android:screenOrientation属性值来实现。
比如下列设置android:screenOrientation="portrait"则无论手机如何变动,拥有这个属性的activity都将是竖屏显示。
android:screenOrientation="landscape",为横屏显示。
上述修改也可以在Java代码中通过类似如下代码来设置setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LAND SCAPE)另外,android中每次屏幕的切换动会重启Activity,所以应该在Activity销毁前保存当前活动的状态,在Activity再次Create的时候载入配置,那样,进行中的游戏就不会自动重启了!二、横竖屏切换如果要让软件在横竖屏之间切换,由于横竖屏的高宽会发生转换,有可能会要求不同的布局。
可以通过以下两种方法来切换布局:1)在res目录下建立layout-land和layout-port目录,相应的layout 文件名不变,比如main.xml。
layout-land是横屏的layout,layout-port是竖屏的layout,其他的不用管,横竖屏切换时程序为调用Activity 的onCreate方法,从而加载相应的布局。
2)假如布局资源不按照如上设置,则可以通过java代码来判断当前是横屏还是竖屏然后来加载相应的xml布局文件。
因为当屏幕变为横屏的时候,系统会重新呼叫当前Activity的onCreate方法,你可以把以下方法放在你的onCreate中来检查当前的方向,然后可以让你的setContentView来载入不同的layout xml。
android中Activity横竖屏切换的那些事讲解之前需要说明的是旋转屏幕:在系统的⾃动旋转屏幕开启的情况下,我们旋转屏幕⼿动设置屏幕:我们⾃⼰去调⽤Activity的 setRequestedOrientation ⽅法。
设置屏幕的⽅向简介值描述unspecified默认值。
系统⾃动选择屏幕⽅向behind跟activity堆栈中的下⾯⼀个activity的⽅向⼀致landscape横屏⽅向,显⽰的宽⽐⾼长portrait竖屏⽅向,显⽰的⾼⽐宽长sensor由设备的物理⽅向传感器决定,如果⽤户旋转设备,这屏幕就会横竖屏切换nosensor忽略物理⽅向传感器,这样就不会随着⽤户旋转设备⽽横竖屏切换了("unspecified"设置除外)user⽤户当前⾸选的⽅向reverseLandscape API 9 以上,反向横屏reversePortrait API 9 以上,反向竖屏sensorLandscape API 9 以上,横屏,但是可以根据物理⽅向传感器来切换正反向横屏sensorPortrait API 9 以上,竖屏,但是可以根据物理⽅向传感器来切换正反向竖屏fullSensor API 9 以上,上下左右四个⽅向,由物理⽅向传感器决定locked API 18 以上,锁死当前屏幕的⽅向第⼀种我们可以在AndroidManifest 清单⽂件⾥⾯制定Activity的⽅向<activityandroid:name=".view.main.MainActivity"android:screenOrientation="portrait"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="UNCHER"/></intent-filter></activity>这样横竖屏切换的时候不会重新创建Activity第⼆种setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);Android:android:configChanges如果我们不配置configuration ,当 configuration 发⽣变化的时候,activity会⾃动处理它。
android横竖屏切换、键盘推出状态改变的处理背景介绍:在编写android小应用的时候,碰到了这样的一个问题:当推开手机的实体键盘时,屏幕由竖屏转换为横屏,此时应用程序的显示界面(Activity)就会被销毁了,这个让人比较郁闷。
如何才能让这个activity不被销毁呢?------------------------------------- 背景分割线 ---------------------------------------------资料查询:在android开发网上有这么几段话:If the configuration of the device (as defined by the Resources.Configuration class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of onPause(),onStop(), and onDestroy()as appropriate. If the activity had been in the foreground or visible to the user, once onDestroy() is called in that instance then a new instance of the activity will be created, with whatever savedInstanceState the previous instance had generated from onSaveInstanceState(Bundle).In some special cases, you may want to bypass restarting of your activity based on one or more types of configuration changes. This is done with the android:configChanges attribute in its manifest. For any types of configuration changes you say thatyou handle there, you will receive a call to your current activity's onConfigurationChanged(Configuration)method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(Configuration) will not be called.To declare that your Activity handles a configuration change, edit the appropriate<activity> element in your manifest file to include the android:configChanges attribute with a string value that represents the configuration that you want to handle. Possible values are listed in the documentation for the android:configChanges attribute (the most commonly used values areorientation to handle when the screen orientation changes and keyboardHidden to handle when the keyboard availability changes). You can declare multiple configuration values in the attribute by separating them with a pipe character ("|").For example, the following manifest snippet declares an Activity that handles both the screen orientation change and keyboard availability change:<activity android:name=".MyActivity"android:configChanges="orientation|keyboardHidden"android:label="@string/app_name">Now when one of these configurations change, MyActivity is not restarted. Instead, the Activity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your Activity's Resources object is updated to return resourcesbased on the new configuration, so you can easily reset elements of your UI without the system restarting your Activity.------------------------------------ 分割线 -----------------------------------------解决办法:通过上面资料的阅读,解决办法就很简单了。
android开发中怎么指定程序屏幕方向
在android开发中,有时候我们开发的应用需要屏幕方向横屏显示,比如某些游戏,这时候我们就需要对指定程序进行一下配置。
android开发中指定程序屏幕方向的方法其实很简单,下面由店铺告诉你!
android开发中指定程序屏幕方向的方法
首先我们来运行一个简单的helloworld程序看看,默认的显示是竖屏的。
首先在我们开发的程序目录里找到AndroidMainfest.xml文件。
点击这个文件进行代码编辑。
找到“activity”标签,在里面加上如下一行代码
android:screenOrientation="landscape"
保存以后,我们运行看看效果。
可以看到现在是横屏显示的状态了。
这里可以设置的参数主要有三个:竖直,水平和自适应。
END。
android实现在横竖屏切换时页⾯信息不被重置的⽰例分享当屏幕转动切换的时候 Android 机制是:销毁当前屏幕的 Activity ,然后重新开启⼀个新的适应屏幕改变的 Activity 。
那么,我们该如何在屏幕切换的时候页⾯信息不被重置呢?解决实现:1.在 AnroidMainifest.xml 的 activity 元素中加⼊:复制代码代码如下:android:configChanges="orientation|keyboardHidden"或复制代码代码如下:android:configChanges="orientation|keyboard|keyboardHidden"表⽰在改变屏幕⽅向、弹出软件盘和隐藏软键盘时,不再去执⾏ onCreate() ⽅法,⽽是直接执⾏ onConfigurationChanged() 。
如果不申明此段代码,按照Activity的⽣命周期,都会去执⾏⼀次 onCreate() ⽅法,⽽ onCreate() ⽅法通常会在显⽰之前做⼀些初始化⼯作。
所以如果改变屏幕⽅向这样的操作都去执⾏ onCreate() ⽅法,就有可能造成重复的初始化,降低程序效率是必然的了,⽽且更有可能因为重复的初始化⽽导致数据的丢失。
这是需要避免的!2.权限声明:复制代码代码如下:<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>API 中说该权限允许我们改变配置信息,但是我们在改变屏幕⽅向的程序中却并没有⽤到该权限,是不是相互冲突了呢?这⾥我们可以这样认为,当我们声明该权限的的时候,系统允许我们通过重写 activity 中的 onConfigurationChanged ⽅法来捕获和修改某些配置信息。
Android实现屏幕旋转⽅法总结本⽂实例总结了Android实现屏幕旋转⽅法。
分享给⼤家供⼤家参考。
具体如下:在介绍之前,我们需要先了解默认情况下android屏幕旋转的机制:默认情况下,当⽤户⼿机的重⼒感应器打开后,旋转屏幕⽅向,会导致当前activity发⽣onDestroy-> onCreate,这样会重新构造当前activity和界⾯布局,如果在Camera界⾯,则表现为卡顿或者⿊屏⼀段时间。
如果是在横竖屏UI设计⽅⾯,那么想很好地⽀持屏幕旋转,则建议在res中建⽴layout-land和layout-port两个⽂件夹,把横屏和竖屏的布局⽂件分别放⼊对应的layout⽂件夹中。
了解了这些以后,我们对android的屏幕旋转⽅法进⾏如下总结:1. AndroidManifest.xml设置如果单单想设置横屏或者竖屏,那么只需要添加横竖屏代码:android:screenOrientation="landscape"横屏设置;android:screenOrientation="portrait"竖屏设置;这种⽅法的优点:即使屏幕旋转,Activity也不会重新onCreate。
缺点:屏幕只有⼀个⽅向。
2. 代码动态设置如果你需要动态改变横竖屏设置,那么,只需要在代码中调⽤setRequestedOrientation()函数:setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏设置setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏设置setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);//默认设置这种⽅法优点:可以随意动态设置,满⾜我们⼈为改变横竖屏的要求,同时满⾜横竖屏UI不同的设计需求;缺点:如果改变设置,那么,Activity会被销毁,重新构建,即重新onCreate;3. 重写onConfigurationChanged如果你不希望旋转屏幕的时候Activity被不断的onCreate(这种情况往往会造成屏幕切换时的卡顿),那么,可以使⽤此⽅法:⾸先,在AndroidMainfest.xml中添加configChanges:<activity android:name=".Test"android:configChanges="orientation|keyboard"></activity>注意,keyboardHidden表⽰键盘辅助功能隐藏,如果你的开发API等级等于或⾼于13,还需要设置screenSize,因为screenSize会在屏幕旋转时改变;android:configChanges="keyboardHidden|orientation|screenSize"然后,在Activity中重写onConfigurationChanged⽅法,这个⽅法将会在屏幕旋转变化时,进⾏监听处理:public void onConfigurationChanged(Configuration newConfig) {// TODO Auto-generated method stubsuper.onConfigurationChanged(newConfig);if (newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){// Nothing need to be done here} else {// Nothing need to be done here}}这个⽅法的优点:我们可以随时监听屏幕旋转变化,并对应做出相应的操作;缺点:它只能⼀次旋转90度,如果⼀下⼦旋转180度,onConfigurationChanged函数不会被调⽤。
我们今天主要讲的就是,我们在用android手机上玩游戏的时候,会有一个方向键,以前的可能大家看见过,想一个十字架,这个只能确定的是四个方向,而现在我们开始用一个和psp的摇杆来代替原先的十字架方向键了。
现在这个方向键是以后发展的趋势,那么就不多说了,我们还是来看看代码吧:我们先来看看mainactivity代码:java代码:1.package eoe.demo;2.3.import android.app.Activity;4.import android.os.Bundle;5.import android.view.Window;6.import android.view.WindowManager;7.8.public class MainActivity extends Activity {9./** Called when the activity is first created. */10.@Override11.public void onCreate(Bundle savedInstanceState) {12.super.onCreate(savedInstanceState);13.this.getWindow().setFlags(youtParams.FLAG_FULLSCREEN,youtParams.FLAG_FULLSCREEN);14.this.requestWindowFeature(Window.FEATURE_NO_TITLE);15.setContentView(new MySurfaceView(this));16.}17.18.}复制代码我们现在要说的就是很重要的代码了:java代码:1.package eoe.demo;2.3.import android.content.Context;4.import android.graphics.Canvas;5.import android.graphics.Color;6.import android.graphics.Paint;7.import android.util.Log;8.import android.view.MotionEvent;9.import android.view.SurfaceHolder;10.import android.view.SurfaceView;11.import android.view.SurfaceHolder.Callback;12.13.public class MySurfaceView extends SurfaceView implements Callback, Runnable {14.15.private Thread th;16.private SurfaceHolder sfh;17.private Canvas canvas;18.private Paint paint;19.private boolean flag;20.//固定摇杆背景圆形的X,Y坐标以及半径21.private int RockerCircleX = 100;22.private int RockerCircleY = 100;23.private int RockerCircleR = 50;24.//摇杆的X,Y坐标以及摇杆的半径25.private float SmallRockerCircleX = 100;26.private float SmallRockerCircleY = 100;27.private float SmallRockerCircleR = 20;28.29.public MySurfaceView(Context context) {30.super(context);31.Log.v("Himi", "MySurfaceView");32.this.setKeepScreenOn(true);33.sfh = this.getHolder();34.sfh.addCallback(this);35.paint = new Paint();36.paint.setAntiAlias(true);37.setFocusable(true);38.setFocusableInTouchMode(true);39.}40.41.public void surfaceCreated(SurfaceHolder holder) {42.th = new Thread(this);43.flag = true;44.th.start();45.}46.47./***48.* 得到两点之间的弧度49.*/50.public double getRad(float px1, float py1, float px2, float py2) {51.//得到两点X的距离52.float x = px2 - px1;53.//得到两点Y的距离54.float y = py1 - py2;55.//算出斜边长56.float xie = (float) Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));57.//得到这个角度的余弦值(通过三角函数中的定理:邻边/斜边=角度余弦值)58.float cosAngle = x / xie;59.//通过反余弦定理获取到其角度的弧度60.float rad = (float) Math.acos(cosAngle);61.//注意:当触屏的位置Y坐标<摇杆的Y坐标我们要取反值-0~-18062.if (py2 < py1) {63.rad = -rad;64.}65.return rad;66.}67.68.@Override69.public boolean onTouchEvent(MotionEvent event) {70.if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() ==MotionEvent.ACTION_MOVE) {71.// 当触屏区域不在活动范围内72.if (Math.sqrt(Math.pow((RockerCircleX - (int) event.getX()), 2) +Math.pow((RockerCircleY - (int) event.getY()), 2)) >= RockerCircleR) {73.//得到摇杆与触屏点所形成的角度74.double tempRad = getRad(RockerCircleX, RockerCircleY, event.getX(), event.getY());75.//保证内部小圆运动的长度限制76.getXY(RockerCircleX, RockerCircleY, RockerCircleR, tempRad);77.} else {//如果小球中心点小于活动区域则随着用户触屏点移动即可78.SmallRockerCircleX = (int) event.getX();79.SmallRockerCircleY = (int) event.getY();80.}81.} else if (event.getAction() == MotionEvent.ACTION_UP) {82.//当释放按键时摇杆要恢复摇杆的位置为初始位置83.SmallRockerCircleX = 100;84.SmallRockerCircleY = 100;85.}86.return true;87.}88.89./**90.*91.* @param R92.* 圆周运动的旋转点93.* @param centerX94.* 旋转点X95.* @param centerY96.* 旋转点Y97.* @param rad98.* 旋转的弧度99.*/100.public void getXY(float centerX, float centerY, float R, double rad) {101.//获取圆周运动的X坐标102.SmallRockerCircleX = (float) (R * Math.cos(rad)) + centerX;103.//获取圆周运动的Y坐标104.SmallRockerCircleY = (float) (R * Math.sin(rad)) + centerY;105.}106.107.public void draw() {108.try {109.canvas = sfh.lockCanvas();110.canvas.drawColor(Color.WHITE);111.//设置透明度112.paint.setColor(0x70000000);113.//绘制摇杆背景114.canvas.drawCircle(RockerCircleX, RockerCircleY, RockerCircleR, paint);115.paint.setColor(0x70ff0000);116.//绘制摇杆117.canvas.drawCircle(SmallRockerCircleX, SmallRockerCircleY, SmallRockerCircleR, paint);118.} catch (Exception e) {119.// TODO: handle exception120.} finally {121.try {122.if (canvas != null)123.sfh.unlockCanvasAndPost(canvas);124.} catch (Exception e2) {125.126.}127.}128.}129.130.public void run() {131.// TODO Auto-generated method stub132.while (flag) {133.draw();134.try {135.Thread.sleep(50);136.} catch (Exception ex) {137.}138.}139.}140.141.public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {142.Log.v("Himi", "surfaceChanged");143.}144.145.public void surfaceDestroyed(SurfaceHolder holder) {146.flag = false;147.Log.v("Himi", "surfaceDestroyed");148.}149.}复制代码我们来接上一篇的代码来说说这个触摸方向键,我们先来看看AndroidManifest.xml中的代码:java代码:1.<?xml version="1.0" encoding="utf-8"?>2.<manifest xmlns:android="/apk/res/android"3.android:versionCode="1"4.android:versionName="1.0" package="eoe.demo">5.<application android:icon="@drawable/icon" android:label="@string/app_name">6.<activity android:name=".MainActivity"7.android:label="@string/app_name">8.<intent-filter>9.<action android:name="android.intent.action.MAIN" />10.<category android:name="UNCHER" />11.</intent-filter>12.</activity>13.14.</application>15.16.17.</manifest>复制代码我们来看看xml代码:java代码:1.<?xml version="1.0" encoding="utf-8"?>2.<LinearLayout xmlns:android="/apk/res/android"3.android:orientation="vertical"4.android:layout_width="fill_parent"5.android:layout_height="fill_parent"6.>7.<TextView8.android:layout_width="fill_parent"9.android:layout_height="wrap_content"10.android:text="@string/hello"11./>12.</LinearLayout>复制代码我们最后来看看效果图:。
Android获取屏幕方向及键盘状态的小例子,android 获取屏幕方向
复制代码代码如下:configuration config = getresources().getconfiguration();if (config.orientation == configuration.orientation_landscape){//横屏,比如
480x320}else if(config.orientation == configuration.orientation_portrait){//竖屏,标准模式320x480}else if(config.hardkeyboardhidden ==
configuration.keyboardhidden_no){//横屏,android123提示物理键盘滑出了}else if(config.hardkeyboardhidden == configuration.keyboardhidden_yes){//竖屏,键盘隐藏了}
您可能感兴趣的文章:
1. android获取屏幕的长与宽实现代码(手写)
2. android获取屏幕像素思路及代码
3. android 获取屏幕像素大小的正确方法
4. android 获取屏幕高度,标题高度,状态栏高度(实例代码)
5. android获取屏幕高度和宽度的实现方法
6. android 获取屏幕尺寸
7. android获取屏幕尺寸大小代码实例
8. android使用service和activity获取屏幕尺寸的方法
9. android编程获取屏幕宽高与获取控件宽高的方法
10. android获取常用辅助方法(获取屏幕高度、宽度、密度、通知栏高度、
截图)
11. android获取屏幕或view宽度和高度的方法
12. android 四种获取屏幕宽度的方法总结。