首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以编程方式在相对布局中定位按钮

以编程方式在相对布局中定位按钮
EN

Stack Overflow用户
提问于 2012-09-27 16:38:37
回答 1查看 7.8K关注 0票数 2

这是我正在使用的布局XML。

代码语言:javascript
复制
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/tabTransparent"
    android:id="@+id/aLayoutRelative">

    <LinearLayout
        android:id="@+id/linearLayout8"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/linearLayout7"
        android:layout_below="@+id/linearLayout7"
        android:layout_marginTop="14dp" >

        <Button
            android:id="@+id/button5"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/text_accounts_aHistoryNotes" />
    </LinearLayout>

</RelativeLayout>

我想以编程的方式在java源码中添加按钮。这就是我尝试过的。

代码语言:javascript
复制
RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.aLayoutRelative);
LinearLayout lastLinearLayout = (LinearLayout)findViewById(R.id.linearLayout8);
lastLinearLayout.setOrientation(LinearLayout.HORIZONTAL);

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT,       LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.LEFT_OF, lastLinearLayout.getId());
layoutParams.addRule(RelativeLayout.BELOW, lastLinearLayout.getId());
layoutParams.setMargins(0, 14, 0, 0);
linearLayout.setLayoutParams(layoutParams);

Button button9 = new Button(this);
Log.i("tab0", recordTabs.get(0));
button9.setText(""+recordTabs.get(0));
button9.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
linearLayout.addView(button9);
relativeLayout.addView(linearLayout);

但在视图中,按钮是垂直的,上面没有文本;对齐到页面的左侧(实际上是相对布局)。XML版本工作得很好。我认为方向设置是罪魁祸首。在谷歌上搜索各种文档也没什么帮助。

有什么想法吗?

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-27 17:00:57

你想要达到什么目的?

对于start,删除

代码语言:javascript
复制
layoutParams.addRule(RelativeLayout.LEFT_OF, lastLinearLayout.getId());

所以你至少可以看到下面的按钮。

为什么要将按钮放在线性布局中?

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12617298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档