您的位置:首页 > 其它

安卓学习笔记-屏幕适配问题0px解决方法

2016-04-15 18:29 417 查看

关于屏幕适配的0px解决方法

遇到的问题

今天在学习安卓开发的时候,想要实现一下平常经常在大部分应用会见到的底部导航栏的效果,比如qq,淘宝等。

大体的思路是:

底部使用LinearLayout在其水平方向添加四个button

上部使用fragment,利用底部的四个button通过设置OnClickListener进行切换

当然实现是相当简单的,使用dp在测试机上很容易就实现了,代码就不贴出来了。

然而很容易就想到了这样在不同机器上很容易就产生问题。主要是因为就算是使用dp这个单位,也有可能在不同机器上占用不同的比例

例如:

<View
android:layout_width="10dp"
android:layout_height="1px"
/>


简单的利用View画一条线在不同设备上都可能产生不同的宽度比例。

那么,作为一只追求”通用代码”的程序猿,绝对不会容忍这样的事情放生的。

解决方法

通过翻阅无数大神的博客,终于找到了一种方法:通过0px和layout_weight来调整布局在某一方向上的比例;

那么今天的问题就很好解决了,代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="mypro.whutos.com.mypro.MainActivity"
android:id="@+id/ll">

<FrameLayout
android:id="@+id/frag_contain"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="9">

</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:orientation="vertical"
android:layout_alignParentBottom="true">
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#000000"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="1px">
<Button
android:layout_width="0px"
android:layout_weight="1"
android:layout_height="match_parent"
android:text="first"
/>
<Button
android:layout_width="0px"
android:layout_height="match_parent"
android:text="sec"
android:layout_weight="1"/>
<Button
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="third"/>
<Button
android:layout_width="0px"
android:layout_weight="1"
android:layout_height="match_parent"
android:text = "forth" />
</LinearLayout>
</LinearLayout>
</LinearLayout>


通过将需要调整的View或ViewGroup的height设置成0px,再将layout_weight设置成相应比例。这样无论什么设备上竖直方向都会按照9:1的比例显示了。

但是在使用的时候还是发现了一些注意的地方

似乎只有在parent为LinearLayout的时候子布局才会出现layout_weight属性

当长宽都设置成0px的时候这个View就消失了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  安卓开发