2012-07-13 72 views
0

我有一個線性佈局(水平)TextView和ImageButton。我有的總寬度是300像素。按鈕圖像是50x50。我可以用於文本的最大寬度爲250.如果文本寬度小於250像素,則下面的代碼可以很好地工作(WRAP_CONTENT工作正常)。android佈局 - 從右到左的WRAP_CONTENT可能嗎?

// create relative layout for the entire view 
    LinearLayout layout = new LinearLayout(this); 
    layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
      LayoutParams.WRAP_CONTENT)); 
    layout.setOrientation(LinearLayout.HORIZONTAL); 

    // create TextView for the title 
    TextView titleView = new TextView(this); 
    titleView.setText(title); 
    layout.addView(titleView); 

    // add the button onto the view 
    bubbleBtn = new ImageButton(this); 
    bubbleBtn.setLayoutParams(new LayoutParams(
      LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT)); 
    layout.addView(bubbleBtn); 

問題出現時,文本佔用超過250像素。按鈕被推出並在300像素空間內變得不可見。

我想要的是:爲圖像分配50像素的寬度。 WRAP_CONTENT在剩下的250個像素中。換句話說,不是從左側填充,而是從右側填充。 Gravity在這種情況下是正確的嗎?如何以及在哪裏應該在代碼中使用它?

還有其他更好的方法嗎?

+0

嘗試文本視圖的最大寬度財產 – Som 2012-07-13 10:44:23

+0

@zolio:不要使用絕對像素,除非必要,你知道你在做什麼(換句話說,只有一個靶向特定設備) 。使用'LinearLayouts'和'layout_weight'來允許Android分配屏幕的百分比。 – Squonk 2012-07-13 10:48:03

回答

1

使用RelativeLayout而不是LinearLayout。設置每個視圖的LayoutParams如下:

// add the button onto the view 
bubbleBtn = new ImageButton(this); 
bubbleBtn.setId(1); // should set this using a ids.xml resource really. 
RelativeLayout.LayoutParams bbLP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
bbLP.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 
bbLP.addRule(RelativeLayout.CENTER_VERTICAL); 
layout.addView(bubbleBtn, bbLP); 

// create TextView for the title 
TextView titleView = new TextView(this); 
titleView.setText(title); 
titleView.setGravity(Gravity.RIGHT); 
RelativeLayout.LayoutParams tvLP = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 
tvLP.addRule(RelativeLayout.LEFT_OF, 1); 
tvLP.addRule(RelativeLayout.CENTER_VERTICAL); 
layout.addView(titleView, tvLP); 
+0

請參閱這篇文章以瞭解如何以編程方式最佳設置ID:http://stackoverflow.com/questions/3216294/android-programatically-add-id-to-r-id – nmw 2012-07-14 08:42:50