Laís Minchillo
Laís Minchillo

Reputation: 761

Programmatically adding an ImageView relative to another one (Android)

I'm trying to programmatically add an ImageView then add another one that is relative to this one. My code:

RelativeLayout mLayout = (RelativeLayout) findViewById(R.id.myLayout);
ImageView anchor = new ImageView(getApplicationContext());
anchor.setImageDrawable(getResources().getDrawable(R.drawable.anchor));
anchor.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams anchorParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
anchorParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
anchorParams.addRule(RelativeLayout.CENTER_VERTICAL);   
mLayout.addView(anchor,anchorParams);
ImageView spinner = new ImageView(getApplicationContext());
spinner.setImageDrawable(getResources().getDrawable(R.drawable.image1));
spinner.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams spinnerParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
spinnerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
spinnerParams.addRule(RelativeLayout.BELOW,anchor.getId());
mLayout.addView(spinner,spinnerParams);

The first image is just where I want it - centralized - but the second one doesn't appear below the anchor, instead it appears at the top of the screen, just below the status bar.

Did I miss anything?

Upvotes: 2

Views: 2501

Answers (3)

mayu
mayu

Reputation: 221

i think, you get null for anchor.getId(). Set a Id for your anchor view, before addRule()

Upvotes: 3

Max Usanin
Max Usanin

Reputation: 2499

It is difficult to say what is wrong, try to make XML and add it

LinearLayout myLayout = (LinearLayout) findViewById(R.id.LogoView);

                View hiddenInfo = getLayoutInflater().inflate(R.layout.search,
                        myLayout, false);
                myLayout.removeAllViews();
                myLayout.addView(hiddenInfo);

Upvotes: 0

nt-complete
nt-complete

Reputation: 519

I believe you need to programmatically give anchor an id before you can use anchor.getId() using anchor.setId(int).

Upvotes: 1

Related Questions