尝试在网格布局中获取几行按钮。
按钮尺寸正常,但边距似乎已经破碎。
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);
答案 0 :(得分:4)
视图的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;