簡體   English   中英

如何將FrameLayout放置在RelativeLayout中

[英]How to center an FrameLayout in a RelativeLayout

我的布局存在問題,如果一些Android專家可以檢查並幫助我,那將是很好的:)

我有一個FragmentA,其中包含另一個FragmentB。

  • FragmentA包含3個FrameLayouts:

      1. FrameLayout:應位於頂部
      1. FrameLayout:應位於第一個包含FragmentB (id = frame2)之下
      1. FrameLayout:應位於底部
  • FragmentB還包含1個FrameLayout:

    • 我以這種方式以編程方式向該FrameLayout添加視圖(例如圖像):

frameLayout.addView(new ImageClass(id);

問題是圖像沒有在中間水平居中。

這是第一個fragmentA的布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frame1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <FrameLayout
        android:id="@+id/frame2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/frame1" />

    <FrameLayout
        android:id="@+id/frame3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />

</RelativeLayout>

這是fragmentB的布局文件(包含在ID為frame2的FragmentA-> FrameLayout 2中)

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imageClass"
    android:background="#0000FF"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</FrameLayout>

並使用以下代碼通過畫布將圖像插入視圖中:

Bitmap image= BitmapFactory.decodeResource(getResources(), id);
canvas.drawBitmap(image, 0, 0, null);

我以為RelativeLayout中的android:gravity="center_horizontal"FragmentAFragmentB兩個FrameLayouts中的android:layout_width="wrap_content"都應將圖像居中。 但這是在左側。

屏幕快照有兩個(第一幅)和外觀(第二幅):

看起來如何

它應該看起來如何

對不起,鏈接,但我無法發布圖片(信譽不足)

RelativeLayouts處理重力的方式與您預期的不同( 鏈接 ):

請注意,由於RelativeLayout認為每個孩子相對於彼此的位置都很重要,因此設置重力會影響所有孩子作為父元素內單個單元的位置。 這種情況發生在孩子的位置相對較高之后。

一個快速的解決方法是將frame2從FrameLayout更改為RelativeLayout,添加match_parent寬度,然后將您的中心重力放在該位置上。

    <RelativeLayout
        android:id="@+id/frame2"
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/frame1"/>

根據視圖的要求,您可以采用多種其他方法。 通常最好避免嵌套RelativeLayouts,但在您的情況下可能有必要。

這里可能重復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM