Rob
Rob

Reputation: 16002

Android : How to set TextViews positions depending on other ones programatically?

I want to put elements in my view depending on the position of the other ones. Let me explain : First, I have two textviews and I've put successfully the second (villeOffre) one under the first one (titreOffre) :

titreOffre = (TextView) findViewById(R.id.offreTitre);
titreOffre.setText(capitalizedString(offre.getTitle()));
villeOffre = (TextView) findViewById(R.id.offreVille);
villeOffre.setText(offre.getLocality());
infos = (TextView) findViewById(R.id.infos);

ViewTreeObserver vto = titreOffre.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(
{
    @Override
    public void onGlobalLayout()
    {
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) villeOffre.getLayoutParams();
        params.setMargins(15,titreOffre.getBottom()+12,15,0);
        villeOffre.setLayoutParams(params);
        titreOffre.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
});

This works perfectly, but now I want to put a third textview (infos) which is depending on villeOffre position. How to do that ?

Thanks a lot.

Upvotes: 0

Views: 423

Answers (1)

SALMAN
SALMAN

Reputation: 2031

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rr = new RelativeLayout(this);

        b1 = new Button(this);
        b1.setId(R.id.Button01);
        recent = b1;
        b1.setText("Click me");
        rr.addView(b1);


        setContentView(rr);

        b1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                tv1 = new TextView(can.this);
                tv1.setId((int)System.currentTimeMillis());
                lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                lp.addRule(RelativeLayout.BELOW, recent.getId());
                tv1.setText("Time: "+System.currentTimeMillis());
                rr.addView(tv1, lp);
                recent = tv1;
            }
        });
    }

Upvotes: 3

Related Questions