这是我正在使用的布局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版本工作得很好。我认为方向设置是罪魁祸首。在谷歌上搜索各种文档也没什么帮助。
有什么想法吗?
提前感谢!
发布于 2012-09-27 17:00:57
你想要达到什么目的?
对于start,删除
layoutParams.addRule(RelativeLayout.LEFT_OF, lastLinearLayout.getId());所以你至少可以看到下面的按钮。
为什么要将按钮放在线性布局中?
https://stackoverflow.com/questions/12617298
复制相似问题