【问题标题】:Creating array of button programmatically以编程方式创建按钮数组
【发布时间】:2018-02-26 22:57:24
【问题描述】:

我希望表格布局中有 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" />

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

【问题讨论】:

    标签: android android-layout user-interface


    【解决方案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

    【讨论】:

    • 为什么每次都在for循环中找到线性布局?
    • 哦!对不起,我有些忙。现在我变了。
    • 如何从代码中引用这个样式:?android:attr/buttonBarButtonStyle
    • 我已经更新了代码。但是我不能检查,请检查并回复。
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2011-06-29
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多