我有一个imageview。我想让它的宽度为fill_parent。我想让它的高等于宽度。例如:
<ImageView
android:layout_width="fill_parent"
android:layout_height="whatever the width ends up being" />
在布局文件中,不需要创建自己的视图类,这样的事情可能吗?
谢谢
我有一个imageview。我想让它的宽度为fill_parent。我想让它的高等于宽度。例如:
<ImageView
android:layout_width="fill_parent"
android:layout_height="whatever the width ends up being" />
在布局文件中,不需要创建自己的视图类,这样的事情可能吗?
谢谢
当前回答
2021年7月28日更新,使用AndroidX而不是支持库
首先,确保你的项目导入了AndroidX,按照下面的说明操作。
然后将你的图像包装在一个ConstraintLayout中,它的字段如下:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1" />
</androidx.constraintlayout.widget.ConstraintLayout>
在这里看到的
其他回答
这可以使用LayoutParams来动态设置视图高度,一旦你在运行时知道了视图宽度。你需要使用一个可运行线程,以便在运行时获得视图的宽度,否则你将试图在你知道视图的宽度之前设置高度,因为布局还没有绘制。
下面是我解决问题的例子:
final FrameLayout mFrame = (FrameLayout) findViewById(R.id.frame_id);
mFrame.post(new Runnable() {
@Override
public void run() {
RelativeLayout.LayoutParams mParams;
mParams = (RelativeLayout.LayoutParams) mFrame.getLayoutParams();
mParams.height = mFrame.getWidth();
mFrame.setLayoutParams(mParams);
mFrame.postInvalidate();
}
});
LayoutParams必须是你的视图所在的父视图的类型。我的FrameLayout在xml文件中的RelativeLayout中。
mFrame.postInvalidate();
调用强制视图重绘,而在一个单独的线程比UI线程
光靠布局是做不到的,我试过了。我最终写了一个非常简单的类来处理它,你可以在github上查看。它是一个更大项目的一部分,但一点复制和粘贴就能解决问题(在Apache 2.0下授权)
本质上,你只需要设置高度/宽度等于另一个维度(取决于你想缩放它的方式)
注意:您可以使用scaleType属性在不使用自定义类的情况下将其设置为正方形,但视图的边界超出了可见图像,如果将其他视图放置在其附近,则会产生问题。
在Android中26.0.0 PercentRelativeLayout已弃用。
解决这个问题的最好方法是使用这样的ConstraintLayout:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
android:src="@drawable/you_image"
app:layout_constraintDimensionRatio="1:1"/>
</android.support.constraint.ConstraintLayout>
下面是一个关于如何将ConstraintLayout添加到项目中的教程。
下面是我解决这个问题的方法:
int pHeight = picture.getHeight();
int pWidth = picture.getWidth();
int vWidth = preview.getWidth();
preview.getLayoutParams().height = (int)(vWidth*((double)pHeight/pWidth));
preview - imageView,宽度设置为“match_parent”,scaleType设置为“cropCenter”
在imageView src中设置的位图对象。
这对我来说很有效。
也许这能回答你的问题:
<ImageView
android:id="@+id/cover_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true" />
对于这种特定的情况,您可以忽略scaleType属性。