我试图在线性布局中把这个图片居中,但它不工作,我可以做什么?

1 人不认可

我试图在这个线性布局中使图像居中,但它只向左对齐,我该怎么做才能解决这个问题。

 <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal">
       <ImageView
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:src="@android:drawable/ic_menu_edit" />
 </LinearLayout>
    
android
android-layout
Efiamotu Owolewa
Efiamotu Owolewa
发布于 2021-10-17
2 个回答
hata
hata
发布于 2021-10-18
已采纳
0 人赞同

尝试将 layout_gravity="center" 设置为ImageView,同时将 orientation="vertical" 设置为LinearLayout。

<LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical">
    <ImageView
             android:layout_gravity="center"
             android:layout_width="wrap_content"
             android:layout_height="match_parent"
             android:src="@android:drawable/ic_menu_edit" />
</LinearLayout>

LinearLayout的目的是将多个子视图放置在一条线上,垂直或水平。当你放置一个单一的子视图时,你没有必要使用LinearLayout,但你可以只使用FrameLayout。

<FrameLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
    <ImageView
             android:layout_gravity="center"
             android:layout_width="wrap_content"
             android:layout_height="match_parent"
             android:src="@android:drawable/ic_menu_edit" />
</FrameLayout>
    
it didnt work could you test the code on your end
我看到你用了一个框架布局,我刚试了一下,它起作用了,但当我把布局改为线性时,图像又回到了左边,我还使用了两个子视图,一个是图像,另一个是文本视图。我对文本使用了对齐文本到中心,它移到了中间,但图像却不再移到电影上了。
Akinyemi Jamiu
Akinyemi Jamiu
发布于 2021-10-18
0 人赞同

Add android:gravity="center" to LinearLayout

<LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:gravity="center">
       <ImageView
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:src="@android:drawable/ic_menu_edit" />
 </LinearLayout>

Or Add android:layout_gravity="center" to the ImageView

<ImageView
         android:layout_width="wrap_content"
         android:layout_height="match_parent"