我想做一条包含图像和文本的消息。文本应位于图像的中心。我找到了一些信息并使用了RelativeLayout。我成功重叠图像和文本。但是文字不在图像的中心。我该如何解决?
如果我想用 Java 代码中的图像填充布局,我应该使用 FitXY 吗?
这是代码。
public class MainActivity extends AppCompatActivity {
final static int num = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams layout_params = new RelativeLayout.LayoutParams(400, 150);
layout.setBackgroundResource(R.color.colorAccent);
layout.setLayoutParams(layout_params);
ImageView imageView = new ImageView(this);
imageView.setId(num);
imageView.setImageResource(R.drawable.nac_clear);
RelativeLayout.LayoutParams image_params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
image_params.addRule(RelativeLayout.CENTER_IN_PARENT);
imageView.setLayoutParams(image_params);
TextView textView = new TextView(this);
textView.setText("Center");
textView.setTextSize(30f);
textView.setTextColor(Color.parseColor("#ffffffff"));
RelativeLayout.LayoutParams text_params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
text_params.addRule(RelativeLayout.ALIGN_LEFT, imageView.getId());
text_params.addRule(RelativeLayout.ALIGN_RIGHT, imageView.getId());
text_params.addRule(RelativeLayout.ALIGN_BOTTOM, imageView.getId());
text_params.addRule(RelativeLayout.ALIGN_TOP, imageView.getId());
textView.setLayoutParams(text_params);
layout.addView(imageView);
layout.addView(textView);
setContentView(layout);