为编程添加的视图添加边距

时间:2016-04-06 22:47:28

标签: java android

我每次单击按钮时都会将相同的视图以编程方式添加到gridLayout中,我想为这些添加的视图设置边距,我该怎么做? 我已尝试layoutParams.setMargin(10,10,10,10)theLayout.setPadding(10,10,10,10)

以下是我添加视图的方式:

        gridLayout= (GridLayout)findViewById(R.id.gamehistory);
        Button b = (Button)findViewById(R.id.Button01);
        layoutParams = new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        b.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {

                Button theButton = new Button(MainActivity.this);
                TextView theText = new TextView(MainActivity.this);
                theText.setGravity(Gravity.CENTER_HORIZONTAL);

                LinearLayout theLayout = new LinearLayout(MainActivity.this);
                theLayout.setOrientation(LinearLayout.VERTICAL);
                theLayout.setBackgroundColor(Color.parseColor("#8BAAC3"));
                theLayout.setId(++i);
                theText.setText(theLayout.getId() + "");
                theLayout.addView(theButton);
                theLayout.addView(theText);
                gridLayout.addView(theLayout, layoutParams);
            }
        });

编辑:我将LayoutParams设置为LinearLayout.LayoutParams,因为它不接受GirdLayout.LayoutParams并且它似乎不会影响它。

我需要的是一种为线性布局添加边距的方法我不断添加按钮(theLayout)。

1 个答案:

答案 0 :(得分:1)

而不是像现在一样每次都添加到gridLayout并重复使用相同的布局参数:

gridLayout.addView(theLayout, layoutParams);

您可以简单地接受GridLayout将为每个子项分配一个新的布局参数对象(addView将为您创建),您可以直接修改它:

gridLayout.addView(theLayout);
GridLayout.LayoutParams lp = (GridLayout.LayoutParams) theLayout.getLayoutParams();
lp.setMargins(...)