标题说明了一切。我需要创建一个方形大小View
,其高度完全取决于移动设备宽度(layout_width="match_parent"
)的大小。
是否可以从Android的.xml文件中指定layout_height="...equals to width..."
,或者我必须在运行时执行此操作?
答案 0 :(得分:1)
您可以通过扩展它并在xml中使用自定义类来以编程方式调整视图的大小。例如,我将扩展ImageView
类并返回一个方形图像(通过将高度更改为宽度的大小):
public class SquareImageView extends ImageView {
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Allows the view to resize
* {@inheritDoc}
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(width, width); //setting height same as width here
}
}
如上所述,使用此类将始终生成方形图像,其中高度等于宽度。
在布局文件中使用它:
<com.packagename.SquareImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
但是,您必须处理设备处于横向状态的情况,这样您的宽度将远远大于高度,因此视图不适合。