2014-08-29 70 views
0

权我有相对布局:的Android的RelativeLayout到的programmaticaly

<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> 

,并希望一些文本视图添加进去,我想将它们放在旁边的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); 

但是所有的意见都会出现在左上角。有谁能够帮助我 ?

回答

1

您正在重复使用与所有视图相同的LayoutParams对象,因此它们最终会使用相同的布局参数。见May I reuse LayoutPrams with ViewGroup.addView?

而且你解决这个问题之后,你应该分配一些ID到第一TextView(通过setId()),否则两个TextViews有相同的ID -1,并RelativeLayout可以选择他们的错单处理这个时候:

youParam.addRule(RelativeLayout.RIGHT_OF, tv.getId()); 

UPDATE 其实你真的需要做的这一切编程?考虑将所有这些视图添加到布局XML android:visibility="gone"并在需要时取消隐藏它们。