简体   繁体   中英

Android RelativeLayout + TextView dynamically

I created a layout dynamically, inside TextView I want to display 2. It works, but how can I position the TextView, one right and one left? Thanks

ScrollView sv = new ScrollView(this);

sv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));

RelativeLayout r_layout = new RelativeLayout(this);

r_layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

sv.addView(r_layout);

TextView tv2 = new TextView(this);
TextView tv1 = new TextView(this);

 int id1 = 1;
        tv1.setId(id1);

        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        p.addRule(RelativeLayout.RIGHT_OF, tv1.getId());

        tv2.setText(data.getStringExtra("prodotto"));
        tv1.setText(data.getStringExtra("prodotto"));

        r_layout.addView(tv2, p);



        layout_relativo.addView(sv);

First set ID to your first TextView using setID() method, then you need to add RIGHT_OF rule for 2nd TextView as given below.

RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.RIGHT_OF, tv1.getId());
r_layout.addView(tv2, p);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM