以编程方式创建按钮数组

时间:2018-02-26 14:18:08

标签: android android-layout user-interface

我想在表格布局中按行显示20个按钮。按钮的当前代码是这样的(它们被重复):

<Button
                android:layout_height="wrap_content"
                android:layout_width="10dp"
                android:layout_marginRight="1dp"
                style="?android:attr/buttonBarButtonStyle"
                android:background="@color/colorGreen"
                android:text="1" />

如何在代码中获得相同的内容。特别是我不知道样式元素在这里是如何工作的。

1 个答案:

答案 0 :(得分:1)

 int ButtonStyle = R.style.Your_Button_Style;    
 LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
 layout.setOrientation(LinearLayout.HORIZONTAL);
 for (int i = 1; i <= 20; i++) {
    Button btn = new Button(new ContextThemeWrapper(context,ButtonStyle), 
    null, ButtonStyle);
    btn.setText(" "+i);
    btn.setLayoutParams (new LayoutParams(10, LayoutParams.WRAP_CONTENT)
    layout.addView(btn);
}



 <style name="Your_Button_Style" parent="@android:style/Theme">
<item name="buttonBarStyle">@android:style/ButtonBar</item>
<item name="buttonBarButtonStyle">@android:style/Widget.Button</item>
</style>

详情: Setting style="?android:attr/buttonBarStyle" to parent layout and style="?android:attr/buttonBarButtonStyle" to buttons make them invisible