Wednesday, June 30, 2010

Java Dynamically adding Android Views android:Layout_toRightOf

I found this post really useful today:
http://stackoverflow.com/questions/2305395/laying-out-views-in-relativelayout-programmatically

ex.
RelativeLayout layout = new RelativeLayout(this);
TextView tv1 = new TextView(this);
tv1
.setText("A");
tv1.setId(23);

TextView tv2 = new TextView(this);
tv2
.setText("B");
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
lp
.addRule(RelativeLayout.RIGHT_OF, tv1.getId());

layout
.addView(tv1);
layout
.addView(tv2, lp);



******
you need to provide id's to your child views: tv1.setId(1); tv2.setId(2); Parent views do not automatically assign child views an Id, and the default value for an Id is NO_ID. Id's don't have to be unique in a view hiearchy - so 1, 2, 3, etc are all fine values to use - and you must use them for relative anchoring to work in RelativeLayout