首页 > 解决方案 > Using two spaces to place an object in the middle of the screen in a horizontal linearlayout

问题描述

I saw this link and answer of bakwarte. Center two buttons horizontally

Toni Gamez said, This is for API >= 14.

I tried and saw that it works for level 10, for example. So could this be the right way for all API levels?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_margin="10dp">
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <ImageView
            android:id="@+id/imageView1"
            android:background="@drawable/Icon"
            android:layout_width="100dp"
            android:layout_height="wrap_content" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>
</LinearLayout>

标签: androidandroid-linearlayout

解决方案


Toni Gamez 没有说明为什么答案只适用于 API >= 14,但可能是因为Space小部件是在 API 14 中首次引入的。

如果您从支持库或 Androidx 中获取Space小部件,此技术将适用于 API 10 和其他 API 。


推荐阅读