Reputation: 302
I have Relative layout :
<RelativeLayout
android:id="@+id/show_photo_details_comment_who_liked"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/show_photo_details_comment_who_liked_star"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:src="@drawable/photo_rate_on" />
</RelativeLayout>
and want to add few text views into it, and I want to place them right next to ImageView...
ImageView img = (ImageView) findViewById(R.id.show_photo_details_comment_who_liked_star);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.show_photo_details_comment_who_liked);
RelativeLayout.LayoutParams youParam = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
youParam.addRule(RelativeLayout.CENTER_VERTICAL,RelativeLayout.TRUE);
youParam.addRule(RelativeLayout.RIGHT_OF, img.getId() );
youParam.setMargins(10,0,0,0);
TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(youParam);
tv.setText( getString( R.string.who_liked_you ) );
tv.setTextColor( getResources().getColor(R.color.green) );
rl.addView(tv);
youParam.addRule(RelativeLayout.RIGHT_OF, tv.getId());
youParam.setMargins(0,0,0,0);
tv = new TextView(getApplicationContext());
tv.setLayoutParams(youParam);
tv.setText( "," );
tv.setTextColor( Color.BLACK );
rl.addView(tv);
But all theese views will show up in left top corner. Can anybody help me ?
Upvotes: 0
Views: 81
Reputation: 41301
You are reusing the same LayoutParams
object with all views, so they end up using the same layout params. See May I reuse LayoutPrams with ViewGroup.addView?.
Also after you fix this, you should assign some id to the first TextView
(via setId()
) because otherwise the two TextViews have the same id -1
, and RelativeLayout
may choose the wrong one of them when processing this:
youParam.addRule(RelativeLayout.RIGHT_OF, tv.getId());
UPDATE
Actually do you really need to do all this programmatically? Consider adding all these views to the layout XML with android:visibility="gone"
and unhiding them when needed.
Upvotes: 1