Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set LayoutParams.BELOW programmatically

Tags:

android

I'm trying to set LayoutParams.BELOW programmatically. Here my code:

RelativeLayout layout = new RelativeLayout(this.getActivity());
    layout.setLayoutParams(new RelativeLayout.LayoutParams(
             LayoutParams.FILL_PARENT,
             LayoutParams.FILL_PARENT));
    layout.setBackgroundColor(Color.parseColor("#CCCDCDCD"));

    ImageView imageView = new ImageView(this.getActivity());
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.CENTER_IN_PARENT);
    imageView.setLayoutParams(params);
    imageView.setBackgroundResource(R.drawable.create_template);

    AnimationDrawable frameAnimation = (AnimationDrawable) imageView.getBackground();

    if (frameAnimation != null) {
        frameAnimation.start();
    }

    TextView textView = new TextView(this.getActivity());
    params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.BELOW, imageView.getId());
    textView.setLayoutParams(params);
    textView.setText("Generating information...");

    layout.addView(imageView);
    layout.addView(textView);

    return layout;

But it's not being correctly positioned. Any idea on why it is not well positioned?

like image 633
Sonhja Avatar asked Jan 18 '26 14:01

Sonhja


1 Answers

The ImageView doesn't have an ID. You need to give it one. Either define some constant integer value, or use View.generateViewId(), and call setId() before using it in the layout params:

ImageView imageView = new ImageView(this.getActivity());
imageView.setId(View.generateViewId());
...
params.addRule(RelativeLayout.BELOW, imageView.getId());
like image 93
Karakuri Avatar answered Jan 20 '26 06:01

Karakuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!