我想将View
水平居中放置在Layout
中。我的代码失败了。我该如何解决这个问题?
请参阅我的代码:
LinearLayout LLT = new LinearLayout(context);
LLT.setOrientation(LinearLayout.VERTICAL);
LLT.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//get booktheme by bookID
theme = db.getthemeByID(id);
String themePath = theme.getFilepath();
int resid = getResources().getIdentifier(themePath, "drawable", getPackageName());
//imageView
ImageView imageTheme = new ImageView(context);
imageTheme.setLayoutParams(new LayoutParams(500, 700));
imageTheme.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageTheme.setPadding(0, 20, 0, 10);
imageTheme.setAdjustViewBounds(true);
imageTheme.setImageResource(resid);
LLT.addView(imageTheme);
// add view
VF.addView(LLT);
答案 0 :(得分:0)
你尝试过使用相对布局而不是线性布局吗?
编辑: 如果你想使用相对布局,
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)imageview.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
imageview.setLayoutParams(layoutParams);
(没有测试代码顺便说一句,但我在我的应用程序中使用它,所以这个shld做的工作)
答案 1 :(得分:0)
使用Gravity
中的LayoutParams
功能,如下所示:
LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(500, 700);
layoutParams.gravity=Gravity.CENTER_HORIZONTAL;
imageTheme.setLayoutParams(layoutParams);
将此代码替换为此代码并尝试:
LinearLayout LLT = new LinearLayout(context);
LLT.setOrientation(LinearLayout.VERTICAL);
LLT.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//get booktheme by bookID
theme = db.getthemeByID(id);
String themePath = theme.getFilepath();
int resid = getResources().getIdentifier(themePath, "drawable", getPackageName());
//imageView
ImageView imageTheme = new ImageView(context);
LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(500, 700);
layoutParams.gravity=Gravity.CENTER_HORIZONTAL;
imageTheme.setLayoutParams(layoutParams);
imageTheme.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageTheme.setPadding(0, 20, 0, 10);
imageTheme.setAdjustViewBounds(true);
imageTheme.setImageResource(resid);
LLT.addView(imageTheme);
// add view
VF.addView(LLT);