首页 > 解决方案 > Imageview 卡在 android 布局的顶部

问题描述

我放了两个线性布局,在第一个线性布局下我放了“textview”,在第二个线性布局下我放了“imageview”。但问题是图像视图没有移动,我想要中间的骰子图标。每当我尝试拖动该图标时,它都会卡在布局的左上角。

我不知道出了什么问题,因为我是 android 新手。

看看截图 https://i.stack.imgur.com/SJmEY.png

activity_main.xml

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="@string/Logo"
            android:textAlignment="center"
            android:textColor="#ffffff"
            android:textSize="36sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/five" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.snakes;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

标签: javaandroidxmlandroid-studio

解决方案


您不能在 LinearLayout 中拖动元素。它们按照在布局文件中声明的顺序放置,具体取决于方向设置(水平或垂直)。

在您的情况下,也没有理由有两个这样的线性布局。您可以将两个元素放在第一个元素中,并使用重力属性使图像视图居中(例如重力 =“center_vertical”)。

编辑:我最终自己尝试了,并使用 LinearLayout 中的 RelativeLayout 解决了它。确保 RelativeLayout 与父级的宽度和高度相匹配,然后将 ImageView 居中在 RelativeLayout 内,如下所示:

<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">

<LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_vertical">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        <ImageView
            android:id="@+id/someImage"
            android:orientation="vertical"
            android:layout_centerInParent="true"/>
    </RelativeLayout>
</LinearLayout>


推荐阅读