TableLayout如何在ImageView之间添加间距

TableLayout how to add spacing between ImageView

我要实现如下效果:

不幸的是,这就是我现在所做的:

如何在 ImageView 之间添加空格以获得与第一张图片相同的效果?这是我的代码:

public class MainActivity extends AppCompatActivity {

    private int totalValue = 2000;
    private int currentValue = 180;
    private int rowsNumber = 10;
    private int columnsNumber = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TableLayout tableLayout = findViewById(R.id.tableLayout);


        for (int i = 0; i < 10; i++) {

            TableRow tableRow = new TableRow(this);
            tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT));

            for (int j = 0; j < columnsNumber; j++) {

                ImageView imageView = new ImageView(this);

                imageView.setImageResource(this.getCellDrawableId(i, j, totalValue, currentValue));

                tableRow.addView(imageView, j);
            }

            tableLayout.addView(tableRow, i);
        }
    }


    private int getCellDrawableId(int i, int j, int totalValue, int currentValue) {

        return R.drawable.test;
    }
}
    ImageView imageView = new ImageView(this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    //Enter your margin below:
    lp.setMargins(left, top, right, bottom);

    imageView.setLayoutParams(lp);
    imageView.setImageResource(this.getCellDrawableId(i, j, totalValue, currentValue));
    tableRow.addView(imageView, j);

试试这个,如果对你有帮助请告诉我。

使用 TableRow.LayoutParams lp = new TableRow.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 它将起作用。

            TableRow.LayoutParams lp = new TableRow.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.leftMargin = margin;
            lp.topMargin = margin;
            lp.rightMargin = margin;
            lp.bottomMargin = margin;
            imageView.setLayoutParams(lp);

或者您可以使用 imageView.setPadding(padding, padding, padding, padding);

干杯。