我想垂直设置按钮。我正在尝试下面的东西,但它不起作用。需要帮助。
RelativeLayout body=(RelativeLayout) findViewById(R.id.body);
RelativeLayout.LayoutParams buttonParams =
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
Button btn;
List<Button> allEds = new ArrayList<Button>();
for(int i=0;i<totalSID;i++){
btn = new Button(FaqList.this);
btn.setId(i);
allEds.add(btn);
if(i==0){}
else
buttonParams.addRule(RelativeLayout.BELOW,allEds.get(i-1).getId());
body.addView(btn,buttonParams);
}
添加xml文件。作为参考,你可以通过它。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:scrollbars="vertical"
>
<HorizontalScrollView
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:fillViewport="true"
>
<LinearLayout
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginBottom="20dp"
>
<LinearLayout
android:id="@+id/body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:animateLayoutChanges="true">
</LinearLayout>
</LinearLayout>
</HorizontalScrollView>
</ScrollView>
</LinearLayout
我不确定问题究竟在哪里
答案 0 :(得分:1)
如果要垂直添加按钮,则只需在体内使用LinearLayout而不是RelativeLayout。
int iNumberOfButtons = productTypeList.size();
Button[] dynamicButtons = new Button[iNumberOfButtons];
LinearLayout.LayoutParams paramsButton = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < iNumberOfButtons; i++) {
ProductType productType = productTypeList.get(i);
dynamicButtons[i] = new Button(getActivity());
dynamicButtons[i].setText(productType.getTitleString());
dynamicButtons[i].setId(i);
dynamicButtons[i].setTextSize(15.0f);
dynamicButtons[i].setOnClickListener(this);
dynamicButtons[i].setLayoutParams(paramsButton);
dynamicButtonsLinearLayout.addView(dynamicButtons[i]); // dynamicButtonsLinearLayout is the container of the buttons
}
答案 1 :(得分:0)
使用线性布局而不是相对布局。如果您需要动态添加多个按钮,请根据项目位置使用RecyclerView,您可以随心所欲地使用
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button bt=new Button(this);
bt.setLayoutParams(lparams);
this.m_vwJokeLayout.addView(bt);
答案 2 :(得分:0)
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
relativeParams.addRule(RelativeLayout.BELOW, idOfTheViewBelow);