相对布局。在 Java 代码中重叠图像和文本

RelativeLayout. Overlap Image and Text in Java Code

我想制作一条包含图片和文字的消息。文字应位于图像的中央。我找到了一些信息并使用了 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);
RelativeLayout.LayoutParams text_params = new     RelativeLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
);
text_params.addRule(RelativeLayout.CENTER_IN_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());

注:

如果您使用 FitXY,将不会保留图像的纵横比。图像将被缩放。要以正确的宽高比显示,请使用 FitStart。