2012-07-13 36 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