【发布时间】:2016-03-07 11:03:35
【问题描述】:
我有一个父 LinearLayout,里面有一个 ImageView 和一个孩子 LinearLayout。 LinearLayout 子元素里面有可以有不同长度的文本。我希望 ImageView 始终具有相同的大小 (200dpx200dp) 并且仅在子 LinearLayout 的文本溢出时按比例缩小。
为此,我在 ImageView 子项中使用了 layout_weight 和 maxHeight,但由于 layout_weight,maxHeight 不起作用。当子 LinearLayout 的文本没有溢出时,ImageView 不是平方的,而是显示为矩形。
我该怎么做?
这是代码
<ImageView
android:id="@+id/charImage"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_width="wrap_content"
android:maxWidth="200dp"
android:maxHeight="200dp"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="@drawable/jon_snow" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="vertical">
----some childs----
</LinearLayout>
这就是它应该的样子,一个 square ImageView,下面有一些文本,与文本的长度无关。
我尝试修改自定义 ImageView 的 onMeasure(),但它没有正确调整大小并且占用了 LinearLayout 子项的一些空间并且文本溢出
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = Math.min(widthMeasureSpec, Math.min(heightMeasureSpec, dpToPx(200)));
setMeasuredDimension(height, height);
}
private int dpToPx(int dp){
float density = getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
【问题讨论】:
标签: android android-layout android-studio android-layout-weight