【问题标题】:Programmatically position a button in relative layout以编程方式在相对布局中定位按钮
【发布时间】:2012-09-18 23:57:08
【问题描述】:

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

<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 源代码中以编程方式添加按钮。这是我尝试过的。

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 版本运行良好。我认为方向设置是罪魁祸首。在各种文档中搜索几乎没有帮助。

有什么想法吗?

提前致谢!

【问题讨论】:

  • 这行layoutParams.addRule(RelativeLayout.LEFT_OF, lastLinearLayout.getId()); 不会让你的视图离开屏幕吗?
  • 没有那行代码,我现在可以看到按钮。这些 xml 是使用 eclipse 中的组件设计自动生成的。看到按钮后,我想将按钮的样式设置为小。我该怎么做?

标签: android android-layout button android-widget android-button


【解决方案1】:

你想达到什么目的?

首先,删除

layoutParams.addRule(RelativeLayout.LEFT_OF, lastLinearLayout.getId());

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

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

【讨论】:

  • 设置按钮以适应文本大小(小于整个屏幕宽度)使用 LayoutParams.WRAP_CONTENT 而不是 LayoutParams.FILL_PARENT:
  • 嗯,这就是设计规范。我所说的小按钮的意思是它必须将样式设置为android.R.attr.buttonStyleSmall。我现在得到了答案。我也可以使用按钮对象构造函数。
  • 我还有一个问题要问你。您如何使布局在具有不同屏幕密度的设备中看起来相同?我读到有几点需要注意,例如使用 WRAP_CONTENT 而不是 FILL_PARENT 和使用 dp 而不是 px。然而,即便如此,我还是在较小的屏幕设备中看到了一些对齐泄漏。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 2011-06-06
  • 1970-01-01
相关资源
最近更新 更多