我有以下代码可以动态创建可点击的ImageViews(取决于你可以使它成为2x2 3x3 4x4等的值...) 一切都工作正常,除了我想要imageViews居中,现在他们从屏幕的左边开始。我希望整个图像视图集合位于屏幕的中心。
private void maakLayout() {
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
linearLayout.setLayoutParams(layoutParams);
setContentView(linearLayout);
TextView textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, (2) * 10);
textView.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams layoutTextParams =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutTextParams.topMargin = 50;
layoutTextParams.bottomMargin = 50;
textView.setLayoutParams(layoutTextParams);
textViewScore = textView;
linearLayout.addView(textView);
int k = 0;
for (int i = 0; i < RASTER; i++) {
LinearLayout linearLayout1 = new LinearLayout(this);
//linearLayout1.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(layoutParams);
layoutParams1.gravity = Gravity.CENTER_VERTICAL;
LinearLayout.LayoutParams layoutImageParams =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
linearLayout1.setLayoutParams(layoutImageParams);
linearLayout.addView(linearLayout1);
for (int j = 0; j < RASTER; j++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.back);
imageView.setTag(k);
imageView.setBackgroundResource(R.drawable.border_gray);
LinearLayout.LayoutParams layoutImageParams1 =
new LinearLayout.LayoutParams(70, 70);
layoutImageParams.topMargin = 2;
layoutImageParams.leftMargin = 2;
layoutImageParams1.gravity = Gravity.CENTER_HORIZONTAL;
imageView.setLayoutParams(layoutImageParams1);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
klikopknop((ImageView) v);
}
});
knoppen[k] = imageView;
linearLayout1.addView(imageView);
k++;
}
}
}
答案 0 :(得分:0)
将ImageView的宽度LayoutParams设置为MATCH_PARENT
,将scaleType设置为CENTER_INSIDE
答案 1 :(得分:0)
使用Realtive布局并将您的imageview放在相对布局中。然后添加规则RelativeLayout.CENTER_IN_PARENT。