因为android屏幕尺寸种类繁多,为了使我们的程序在不同的手机屏幕上有相同的显示效果,所以屏幕适配问题就显得格外重要,解决屏幕适配问题可以从以下几方面着手
1. 布局文件
- 布局的时候尽量使用相对布局,尽量使用wrap-content和match-parent表示宽度和高度
- 尽量使用权重设置宽度或者高度
- 组件背景如果是图片的话尽量使用.9图,.9图可根据组件内容的大小伸缩变换
2.限定符的使用 ,使用限定符,系统会自动选择对应分辨率下的资源文件。
① large-layout、layout-sw600dp,例如屏幕为5寸和屏幕为7寸的区别:
适配手机的单面板(默认)布局:res/layout/main.xml
<LinearLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
android:orientation
=
"vertical"
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
>
<fragment
android:id
=
"@+id/headlines"
android:layout_height
=
"fill_parent"
android:name
=
"com.example.android.newsreader.HeadlinesFragment"
android:layout_width
=
"match_parent"
/>
</LinearLayout>
适配尺寸>7寸平板的双面板布局:res/layout-sw600dp/main.xml
<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
android:layout_width=
"fill_parent"
android:layout_height=
"fill_parent"
android:orientation=
"horizontal"
> <fragment android:
id
=
"@+id/headlines"
android:layout_height=
"fill_parent"
android:
name
=
"com.example.android.newsreader.HeadlinesFragment"
android:layout_width=
"400dp"
android:layout_marginRight=
"10dp"
/> <fragment android:
id
=
"@+id/article"
android:layout_height=
"fill_parent"
android:
name
=
"com.example.android.newsreader.ArticleFragment"
android:layout_width=
"fill_parent"
/></LinearLayout>
② 根据屏幕的大小动态的选择加载不同的布局文件,而不同的布局文件很可能会造成我们程序逻辑的变化,最常见的就是单面板和双面板的问题,这就是我们需要解决的问题:
通过判断特定组件的可见与否判断是单面板模式还是双面板模式,这是最简单有效的方法,
public
class
NewsReaderActivity
extends
FragmentActivity
{ boolean mIsDualPane; @Override public void onCreate(
Bundle
savedInstanceState) {
super
.onCreate(savedInstanceState); setContentView(
R
.layout.main_layout);
View
articleView = findViewById(
R
.id.article); mIsDualPane = articleView != null && articleView.getVisibility() ==
View
.
VISIBLE
; }}
而不同的面板模式又影响着我们的逻辑操作,比如单面板模式下,点击某标签我们需要跳转到新的activity,而双面板模式下只需要刷新某一界面而已,此时我们需要考虑不同的面板需要做出不同的操作
@Override
public
void
onHeadlineSelected(
int
index
) { mArtIndex =
index
;
if
(mIsDualPane) {
/* display article on the right pane */
mArticleFragment.displayArticle(mCurrentCat.getArticle(
index
)); }
else
{
/* start a separate activity */
Intent intent =
new
Intent(
this
, ArticleActivity.class); intent.putExtra(
"catIndex"
, mCatIndex); intent.putExtra(
"artIndex"
,
index
); startActivity(intent); }}
3.还有一种百分比的适配方案
以320*480分辨率为基准,生成所有的分辨率对应的像素列表,
- 将屏幕的宽度分为320份,取值为x1~x320
- 将屏幕的高度分为480份,取值为y1~y480
生成的文件如下图:
以这个为基准,把其他的所有的分辨率都补全了,例如1080*1920的,
当然了如果让我们通过计算来实现的话既浪费时间又浪费精力,这里有现成的方法用
https://github.com/hongyangAndroid/Android_Blog_Demos/tree/master/blogcodes/src/main/java/com/zhy/blogcodes/genvalues
。我们只需要将生成的文件放到指定的目录下即可
我这还没有补全,需要注意的值values中必须也有lay_x.xml和lay_y.xml文件,文件内容一般和values-480x320内容一样,否则当出现未补全的分辨率的手机时会报错,无法实现屏幕适配。
使用方法就很简单了:
<
FrameLayout
> <
Button
android:layout_gravity=
"center"
android:gravity=
"center"
android:text=
"@string/hello_world"
android:layout_width=
"@dimen/x160"
android:layout_height=
"@dimen/y160"
/></
FrameLayout
>