添加按钮阵列到GridView在Android应用程序阵列、应用程序、按钮、GridView

2023-09-12 03:30:07 作者:就这么说再见

我有,将有5-15按钮取决于什么是可从后端的应用程序。我如何定义适当的GridView布局文件,以包括将各有不同的文本和其他属性按钮数组?每个按钮将除了其添加到购物车项的项目实质上添加至购物车,所以onClick的code将是相同的。

I have an application that will have 5-15 buttons depending on what is available from a backend. How do I define the proper GridView layout files to include an array of buttons that will each have different text and other attributes? Each button will essentially add an item to a cart, so the onClick code will be the same except for the item it adds to the cart.

我如何定义一个数组,所以我可以添加一个可变数目的按钮,但仍通过一个唯一的ID引用他们每个人的?我见过的 arrays.xml 的例子,但他们已经创建了一个数组是pre-组字符串。我需要一种方法来创建一个对象,而不是在布局或数组的xml文件中定义的文本。

How can I define an array so I can add a variable number of buttons, but still reference each of them by a unique ID? I've seen examples of the arrays.xml, but they have created an array of strings that are pre-set. I need a way to create an object and not have the text defined in the layout or arrays xml file.

更新 - 增加约增加了信息一个GridView

我想要将它添加到一个GridView,所以调用addView方法导致一个UnsupportedOperationException。我能做到以下几点:

I want to add this to a GridView, so calling the addView method results in an UnsupportedOperationException. I can do the following:

ImageButton b2 = new ImageButton(getApplicationContext());
b2.setBackgroundResource(R.drawable.img_3);
android.widget.LinearLayout container = (android.widget.LinearLayout) findViewById(R.id.lay);
container.addView(b2);

但是,这并不布局网格中的按钮像我想。可在GridView这样做?

but that doesn't layout the buttons in a grid like I would like. Can this be done in a GridView?

推荐答案

在以下code,你应该改变的为上限, 给一个变量。

In the following code, you should change the upper limits of the for, to a variable.

public class MainActivity
        extends Activity
        implements View.OnClickListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            TableLayout layout = new TableLayout (this);
            layout.setLayoutParams( new TableLayout.LayoutParams(4,5) );

            layout.setPadding(1,1,1,1);

            for (int f=0; f<=13; f++) {
                TableRow tr = new TableRow(this);
                for (int c=0; c<=9; c++) {
                    Button b = new Button (this);
                    b.setText(""+f+c);
                    b.setTextSize(10.0f);
                    b.setTextColor(Color.rgb( 100, 200, 200));
                    b.setOnClickListener(this);
                    tr.addView(b, 30,30);
                } // for
                layout.addView(tr);
            } // for

            super.setContentView(layout);
        } // ()

        public void onClick(View view) {
            ((Button) view).setText("*");
            ((Button) view).setEnabled(false);
        }
    } // class
 
精彩推荐
图片推荐