Android界面适配机制

来源:互联网 发布:pojdijkstra算法 编辑:程序博客网 时间:2024/04/30 07:17

 自适应

1.首先是建立多个layout文件夹(drawable也一样)

res目录下建立多个layout文件夹,文件夹名称为layout-800x480等。需要适应那种分辨率就写成什么。

注意:

a.较大的数字要写在前面:比如layout-854x480而不能写layout-480x854.

b.两个数字之前是小写字母x,而不是乘号。

2.在不能的layout下调整layout的长宽等各种设置。以适应不同的分辨率。

3最后需要在AndroidManifest.xml里面添加下面一段,没有这一段自适应就不能实现:

</application>


<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:anyDensity = "true"/>


</manifest>


</application>标签和</manifest>标签之间添加上面那段代码。即可

 

drawable- hdpidrawable- mdpidrawable-ldpi的区别:


  (1)drawable-hdpi里面存放高分辨率的图片,WVGA (480x800),FWVGA (480x854)


  (2)drawable-mdpi里面存放中等分辨率的图片,HVGA (320x480)


  (3)drawable-ldpi里面存放低分辨率的图片,QVGA (240x320) 



横屏竖屏自动切换:


可以在res目录下建立layout-port-800x600layout-land两个目录,里面分别放置竖屏和横屏两种布局文件,这样在手机屏幕方向变化的时候系统会自动调用相应的布局文件,避免一种布局文件无法满足两种屏幕显示的问题。


不同分辨率横屏竖屏自动切换:


800x600为例
可以在res目录下建立layout-port-800x600layout-land-800x600两个目录

每个activity都有这个属性screenOrientation,每个activity都需要设置,可以设置为竖屏(portrait),也可以设置为无重力感应(nosensor)。


要让程序界面保持一个方向,不随手机方向转动而变化的处理办法:

AndroidManifest.xml里面配置一下就可以了。加入这一行android:screenOrientation="landscape"
例如(landscape是横向,portrait是纵向):

Java代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ray.linkit"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".GamePlay"
android:screenOrientation="portrait"></activity>
<activity android:name=".OptionView"
android:screenOrientation="portrait"></activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>


另外,android中每次屏幕的切换动会重启Activity,所以应该在Activity销毁前保存当前活动的状态,在Activity再次Create的时候载入配置,那样,进行中的游戏就不会自动重启了!


有的程序适合从竖屏切换到横屏,或者反过来,这个时候怎么办呢?可以在配置Activity的地方进行如下的配置android:screenOrientation="portrait"。这样就可以保证是竖屏总是竖屏了,或者landscape横向。


而有的程序是适合横竖屏切换的。如何处理呢?首先要在配置Activity的时候进行如下的配置:android:configChanges="keyboardHidden|orientation",另外需要重写Activity onConfigurationChanged方法。实现方式如下,不需要做太多的内容:

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// land do nothing is ok
} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
// port do nothing is ok
}
}