我想在我的
relative layout
中并排创建两个元素。这是我的代码:
int pixels = (int) (20 * scale + 0.5f);
ImageView img = new ImageView(candidate_registration_1.this);
TextView text = new TextView(candidate_registration_1.this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(pixels,pixels);
params.addRule(RelativeLayout.ALIGN_PARENT_START,RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_BOTTOM,text.getId());
img.setImageDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.baseline_add_24,getApplicationContext().getTheme()));
img.setLayoutParams(params);
RelativeLayout.LayoutParams params_1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
text.setGravity(Gravity.CENTER);
params_1.addRule(RelativeLayout.ALIGN_TOP,img.getId());
params_1.addRule(RelativeLayout.ALIGN_BOTTOM,img.getId());
params_1.addRule(RelativeLayout.END_OF,img.getId());
params_1.setMarginStart(60);
TextViewCompat.setTextAppearance(text,R.style.sansfont);
text.setText("click");
text.setLayoutParams(params_1);
parent_layout.addView(img);
parent_layout.addView(text);
我期望我的输出是:
实际上是什么:
如您所见,元素没有正确水平对齐,文本似乎略高于图像。我该如何解决这个问题?
尝试设置 TextView 的高度以匹配父级:
RelativeLayout.LayoutParams params_1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.MATCH_PARENT);
附言对于这种用例,ConstraintLayout 现在是一个更好的选择。