2014-08-29 71 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"並在需要時取消隱藏它們。