【发布时间】:2012-07-13 10:43:27
【问题描述】:
我在线性布局(水平)中有一个 TextView 和一个 ImageButton。我的总宽度是 300 像素。按钮图像为 50x50。我可以为文本使用的最大宽度是 250。如果文本宽度小于 250 像素(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 个像素中。换句话说,不是从左边填写,而是从右边填写。在这种情况下使用重力是正确的吗?我应该在代码中如何以及在何处使用它?
或者还有其他更好的方法吗?
【问题讨论】:
-
尝试文本视图的最大宽度属性
-
@zolio :除非必要并且您知道自己在做什么(换句话说,仅针对特定设备),否则切勿使用绝对像素。使用
LinearLayouts和layout_weight允许Android 分配屏幕的百分比。