首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android:gravity=“中心”未按预期工作

Android:gravity=“中心”未按预期工作
EN

Stack Overflow用户
提问于 2016-02-12 18:58:31
回答 2查看 7.4K关注 0票数 5

我有以下xml文件

代码语言:javascript
复制
  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#000000"
              android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="100dp"
        android:orientation="vertical"
        android:background="#ff0000">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00ff00"
            android:text="Button"
            android:layout_gravity="center"/>
    </LinearLayout>

</LinearLayout>

它有以下设计。

button不应该垂直放置在中间吗?我知道layout_gravitygravity是如何工作的。因此,根据我的理解,按钮应该是绝对在中心,无论是水平的还是垂直的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-12 19:02:53

必须在android:gravity="center"中添加LinearLayout

代码语言:javascript
复制
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="100dp"
    android:orientation="vertical"
    android:gravity="center"
    android:background="#ff0000">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#00ff00"
        android:text="Button"
        android:layout_gravity="center"/>
</LinearLayout>

票数 8
EN

Stack Overflow用户

发布于 2016-02-12 19:23:18

基于@vspallas的答案,我找到了我的问题的解决方案。基本上,这种行为的原因是,我将vertical定向指定为LinearLayout。这意味着,我在layout中放置的任何视图都应该以垂直方向显示,即位于另一个下方的视图。如果我的LinearLayout中有三个视图,那么结果应该是这样的

代码语言:javascript
复制
View1
View2
View3.

但是,如果我为View2做了View2,如果它按照我的预期工作,那么它将把View2放在中间,而不是在View1View3之间,这将与orientation属性相矛盾。因此,Android允许将重力设置到父视图本身,这将确保所有视图都继承相同的重力,并且对LinearLayout具有相同的方向。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35370219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档