动态生成的按钮不占用GridLayout中的空间

时间:2016-07-26 13:07:51

标签: java android xml button android-gridlayout

我有一个GridLayout,其中我想要动态生成按钮。我已经指定了行数和数量。 XML中GridLayout的列。我希望生成的按钮占用GridLayout中的大量空间。

也就是说,如果我有三列,则所有三个按钮都应占用相同的空间。现在我在StackOverflow上看到了一些建议使用android:layout_width的示例,但它们都没有包含动态生成的视图和放大器的示例。我不知道是否以及如何将layout_width添加到View组件Button

我希望我的GridLayout看起来像this,但我得到的只是这个

HHH-6615

以下是包含GridLayout

的XML
<GridLayout
                            android:id="@+id/gridLayout"
                            android:layout_marginTop="30dp"
                            android:layout_gravity="center"
                            android:background="@android:color/holo_blue_light"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:columnCount="2"
                            android:rowCount="2"
                            android:columnOrderPreserved="true"
                            android:scrollbars="vertical">
                        </GridLayout>

以下是动态生成Buttons

netbankingGrid = (GridLayout) findViewById(R.id.gridLayout);

        //First Cell on the Grid
        {
            Button button1 = new Button(this);
            button1.setText("Button1");
            Drawable image = getApplicationContext().getResources().getDrawable(R.drawable.ar_hdfc);
            image.setBounds(0,0,70,70);
            button1.setCompoundDrawables(null,image,null, null);
            button1.setBackgroundResource(R.drawable.custom_bg1);
            netbankingGrid.addView(button1);
        }

        //Second Cell on the Grid
        {

            Button button2 = new Button(this);
            button2.setText("Button2");
            Drawable image = getApplicationContext().getResources().getDrawable(R.drawable.ar_hdfc);
            image.setBounds(0,0,70,70);
            button2.setCompoundDrawables(null,image,null, null);
            button2.setBackgroundResource(R.drawable.custom_bg2);
            netbankingGrid.addView(button2);
        }

        //Third Cell on the Grid
        {

            Button button3 = new Button(this);
            button3.setText("Button3");
            Drawable image = getApplicationContext().getResources().getDrawable(R.drawable.ar_hdfc);
            image.setBounds(0,0,70,70);
            button3.setCompoundDrawables(null,image,null, null);
            button3.setBackgroundResource(R.drawable.custom_bg3);
            netbankingGrid.addView(button3);
        }

        //Fourth Cell on the Grid
        {

            Button button4 = new Button(this);
            button4.setText("Button4");
            Drawable image = getApplicationContext().getResources().getDrawable(R.drawable.ar_hdfc);
            image.setBounds(0,0,70,70);
            button4.setCompoundDrawables(null,image,null, null);
            button4.setBackgroundResource(R.drawable.custom_bg4);
            netbankingGrid.addView(button4);
        }

感谢您的时间!

0 个答案:

没有答案