Android - 如何在网格布局中以编程方式设置边距

Android - How to set margins programmatically in gridlayout

尝试在网格布局中获取几行按钮。

按钮大小还可以,但边距似乎破了。

package ray.gui;
import android.app.Activity;
import android.content.pm.*;
import android.graphics.*;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        int size=150;
        int rows=2;
        int columns=5;
        Integer[] colors=new Integer[columns];
        colors[0]=Color.RED;
        colors[1]=Color.YELLOW;
        colors[2]=Color.GREEN;
        colors[3]=Color.BLUE;
        colors[4]=Color.rgb(255,165,0);
        GridLayout gridLayout=new GridLayout(this);
        gridLayout.setRowCount(rows);
        gridLayout.setColumnCount(columns);
        GridLayout.LayoutParams layoutParams=new GridLayout.LayoutParams();
        layoutParams.setMargins(size*30/100,size*30/100,size*30/100,size*30/100);
        gridLayout.setLayoutParams(layoutParams);
        for(int i=0;i<rows*columns;i++) {
            Button button=new Button(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size,size);
            params.width = size;
            params.height= size;
            button.setLayoutParams(params);
            button.setText(""+i);
            //button.setLayoutParams(layoutParams);
            if(i/columns%2==1)
                button.setBackgroundColor(colors[i%columns]);
            gridLayout.addView(button);
        }
        setContentView(gridLayout);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return false;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
}

编辑:下面的代码有效。

    Button button=new Button(this);
    GridLayout.LayoutParams layoutParams=new GridLayout.LayoutParams();
    layoutParams.setMargins(size*20/100,size*20/100,size*20/100,size*20/100);
    layoutParams.width=size;
    layoutParams.height=size;
    button.setLayoutParams(layoutParams);

视图的layoutParams 是供其父级使用的,而不是它自己。所以 gridLayout 的 layoutParams 不应该是 GridLayout.LayoutParams 因为它的父级不是 GridLayout.

尝试替换

    GridLayout.LayoutParams layoutParams=new GridLayout.LayoutParams();
    layoutParams.setMargins(size*30/100,size*30/100,size*30/100,size*30/100);

    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout
            .LayoutParams.WRAP_CONTENT);
    layoutParams.leftMargin = 45;
    layoutParams.rightMargin = 45;
    layoutParams.topMargin = 45;
    layoutParams.bottomMargin = 45;