Search code examples
androidandroid-layoutandroid-relativelayoutandroid-layoutparams

RelativeLayout. Overlap Image and Text in Java Code


I want to make a message which contains a image and text. The text should be on the center of the image. I found some informations and I used RelativeLayout. And I succeed overlap image and text. But the text is not on the center of image. How can I fix that?

And if I want to fill layout with a image in Java Code, should I use FitXY?

Here is code.

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);

Solution

  • RelativeLayout.LayoutParams text_params = new     RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
    );
    text_params.addRule(RelativeLayout.CENTER_IN_PARENT);
    

    And you don't need this:

    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());
    

    Note:

    If you use FitXY, aspect ratio of image will not be retained. Image will be scaled. For display in correct aspect ratio use FitStart.