相对布局重力不起作用

时间:2014-01-03 17:01:22

标签: android android-layout relativelayout

以下是 XML 文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mylayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="bottom" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/whitebar" />

</RelativeLayout>

这是 Java 文件

public class MainActivity extends Activity {

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

    RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.mylayout);
    int images[] = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};

    relativeLayout.setBackgroundResource(images[getRandomNumber()]);
}


private int getRandomNumber() {
    //Note that general syntax is Random().nextInt(n)
    //It results in range 0-4
    //So it should be equal to number of images in images[] array
    return new Random().nextInt(4);
}}

The code above gives an output Current Output

BUT我想要发生的事情与此prospected

类似

如何设置白条图像的确切位置,因为相对布局重力不起作用?

2 个答案:

答案 0 :(得分:2)

布局重力与线性布局一起使用。

您要使用的是alignParentBottom

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mylayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/whitebar" />

</RelativeLayout>

答案 1 :(得分:2)

你应该删除重力并放入ImageView

android:layout_alignParentBottom="true"
相关问题