Android开发琐事

       第一次写博客,不知要写些什么,索性就写一些关于最近学习android开发遇到的问题吧。
       毕竟还是前脚刚迈进android开发门槛不久而后脚不知在哪儿的菜鸟一枚,所掌握的知识必然有限,不必太较真。下面就开始讲我最近遇到的问题吧。
       自去年google宣布放弃eclipse而转战android studio(以下简称AS)开始,许许多多的android开发者开始学习使用AS。首先的一个问题就是关于AS的,有一次,我创建一个项目,结果报出了各种错误,当时我还想,上一次(也就是那天的昨天)用AS创建项目没有任何问题呀,不应该是我配置的环境有问题呀。接下来就看了一下AS给出的提示,说的是什么无法访问某个链接,一下子才想起来电脑没有连接到网络,然后连上网,试了一下,果然问题解决了。所以,小伙伴们在开发android的时候最好连上网,以免遇到类似的情况。
       做android开发必然要对布局文件进行设置,那么就不得不提到一个比较不好理解的属性layout_weight(权重)。首先给出代码

        <TextView
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:background="#ff0"
            android:layout_height="match_parent" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_weight="2"
            android:background="#fff"
            android:layout_height="match_parent" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_weight="3"
            android:background="#f00"
            android:layout_height="match_parent" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_weight="4"
            android:background="#00f"
            android:layout_height="match_parent" />

效果如下
这里写图片描述
显然符合1:2:3:4
如果改成这样呢

        <TextView
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:background="#ff0"
            android:layout_height="match_parent" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_weight="2"
            android:background="#fff"
            android:layout_height="match_parent" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_weight="3"
            android:background="#f00"
            android:layout_height="match_parent" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_weight="4"
            android:background="#00f"
            android:layout_height="match_parent" />

效果如下
这里写图片描述
       结果很是出乎意料,不过还好,已经有很多人总结出了这个原因,下面我就来简要说一下。
       当layout_width设置为wrap_content时,系统先给4个TextView分配他们的宽度值wrap_content(宽度足以包含他们的内容即可),然后会把剩下来的屏幕空间按照1:2:3:4的比列分配给4个Textview,所以就出现了上面的图像。
       而layout_width设置为fill_parent时,系统先给4个Textview分配他们所要的宽度fill_parent,也就是说每一都是填满他的父控件,这里就整个屏幕的宽度
那么这时候的剩余空间=1个parent_width-4个parent_width=-3个parent_width (parent_width指的是屏幕宽度 )
那么第一个TextView的实际所占宽度应该=fill_parent的宽度,即parent_width + 他所占剩余空间的权重比列1/10 * 剩余空间大小(-3 parent_width)=7/10parent_width
同理第二个TextView的实际所占宽度=parent_width + 2/10*(-3parent_width)=4/10parent_width;
第三个TextView的实际所占宽度=parent_width + 3/10*(-3parent_width)=1/10parent_width;
第四个TextView的实际所占宽度=parent_width + 4/10*(-3parent_width)=-2/10parent_width;
故,在图中只能看到第一个TextView和第二个TextView
权重的解释来自http://mobile.51cto.com/abased-375428.htm

猜你喜欢

转载自blog.csdn.net/z190814412/article/details/50467242