【发布时间】: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