RelativeLayout对

问题描述 投票:0回答:1

我正在尝试一个包含三个视图组的应用程序。从RelativeLayout开始,我将使用TextViews。但它不起作用。在下面的代码中,第二个textview随机出现在屏幕上,我发现这是因为rl1.addRule(RelativeLayout.RIGHT_OF, tv.getId());无效。我尝试了rl1.addRule(RelativeLayout.BELOW, bt.getId());并且能够在任何我想要的地方找到它。

        View bt = findViewById(R.id.button);
        TextView tv = new TextView(this);
        tv.setId(0);
        tv.setText("This is a test");
        RelativeLayout.LayoutParams rl = 
                new RelativeLayout.LayoutParams
                (RelativeLayout.LayoutParams.WRAP_CONTENT, 
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        rl.addRule(RelativeLayout.BELOW, bt.getId());
        rl.setMargins(30, 20, 0, 0);
        tv.setLayoutParams(rl);

        rLayout.addView(tv);

        TextView tv1 = new TextView(this);
        tv1.setId(1);
        tv1.setText("still testing this");
        RelativeLayout.LayoutParams rl1 = 
                new RelativeLayout.LayoutParams
                (RelativeLayout.LayoutParams.WRAP_CONTENT, 
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl1.addRule(RelativeLayout.RIGHT_OF, tv.getId());
        rl1.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId());
        rl1.setMargins(30,20,0,0);
        tv1.setLayoutParams(rl1);

        rLayout.addView(tv1);

作为这个代码的结果,我有第一个textView正好在我想要的地方,但第二个在顶部与相对布局对齐,并且水平地在与第一个相同的地方开始(我假设因为两者都有左边30的边距)。

android android-layout android-relativelayout
1个回答
0
投票

当平板电脑处于横向模式时,将此代码放在/res/layout-land文件夹中,用于两个ListView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="horizontal" >

    <ListView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.5" >
    </ListView>


    <ListView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.5" >
    </ListView>

</LinearLayout>

在纵向模式下,xml文件可能如下所示(位于/res/layout-port文件夹中):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</LinearLayout>

编辑:当然两个文件必须具有相同的名称,因此在您的文件命名为setContentView(R.layout.activity_main);时,您必须编写activity_main.xml

© www.soinside.com 2019 - 2024. All rights reserved.