gpt4 book ai didi

java - Android - 如何在 gridlayout 中以编程方式设置边距

转载 作者:搜寻专家 更新时间:2023-11-01 07:51:59 24 4
gpt4 key购买 nike

试图在网格布局中获得几行按钮。

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

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);

最佳答案

View 的布局参数供其父级使用,而不是它自己。所以 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;

关于java - Android - 如何在 gridlayout 中以编程方式设置边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33851268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com