RelativeLayout的。 Java代码中的重叠图像和文本

时间:2018-01-25 02:00:31

标签: android android-layout android-relativelayout android-layoutparams

我想制作一条包含图片和文字的信息。文本应位于图像的中心。我发现了一些信息,我使用了RelativeLayout。我成功地重叠了图像和文本。但文字不在图像的中心。我该如何解决这个问题?

如果我想在Java Code中用图像填充布局,我应该使用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);

1 个答案:

答案 0 :(得分:0)

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。