【发布时间】:2019-01-13 15:58:18
【问题描述】:
背景
这是一个非常简单的问题。
我想让 ImageView 和 TextView 居中,以便 TextView(以及可选的更多视图)位于 ImageView 下方,但应始终显示(如果需要,ImageView 可以按比例缩小,只需保持纵横比)。
问题
由于某种原因,我想过的所有方法都行不通。总有一种情况(通常通过改变方向以减少可用空间很容易重现)TextView 没有显示。
我尝试过的
- 最初,我所做的是这样的:
ic_android_red.xml - 示例图像而不是原始图像。
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:height="400dp"
android:tint="#FF0009" android:viewportHeight="24.0"
android:viewportWidth="24.0" android:width="400dp">
<path android:fillColor="#FF000000"
android:pathData="M6,18c0,0.55 0.45,1 1,1h1v3.5c0,0.83 0.67,1.5 1.5,1.5s1.5,-0.67 1.5,-1.5L11,19h2v3.5c0,0.83 0.67,1.5 1.5,1.5s1.5,-0.67 1.5,-1.5L16,19h1c0.55,0 1,-0.45 1,-1L18,8L6,8v10zM3.5,8C2.67,8 2,8.67 2,9.5v7c0,0.83 0.67,1.5 1.5,1.5S5,17.33 5,16.5v-7C5,8.67 4.33,8 3.5,8zM20.5,8c-0.83,0 -1.5,0.67 -1.5,1.5v7c0,0.83 0.67,1.5 1.5,1.5s1.5,-0.67 1.5,-1.5v-7c0,-0.83 -0.67,-1.5 -1.5,-1.5zM15.53,2.16l1.3,-1.3c0.2,-0.2 0.2,-0.51 0,-0.71 -0.2,-0.2 -0.51,-0.2 -0.71,0l-1.48,1.48C13.85,1.23 12.95,1 12,1c-0.96,0 -1.86,0.23 -2.66,0.63L7.85,0.15c-0.2,-0.2 -0.51,-0.2 -0.71,0 -0.2,0.2 -0.2,0.51 0,0.71l1.31,1.31C6.97,3.26 6,5.01 6,7h12c0,-1.99 -0.97,-3.75 -2.47,-4.84zM10,5L9,5L9,4h1v1zM15,5h-1L14,4h1v1z"/>
</vector>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent" android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_android_red"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</LinearLayout>
在纵向上,效果很好:
但在横向上,它可以避免完全显示 TextView:
我尝试用
NestedScrollView和android:fillViewport="true"包装它,但除了至少滚动到它之外,它没有任何帮助。我尝试将 LinearLayout 分成两半(使用 0px 的权重和高度),以便顶部将 ImageView 设置为底部(我使用 FrameLayout 来包含它),并且底部将具有其余部分,其内容与顶部对齐并水平居中。但后来看起来也很奇怪,也许是因为他们不再真正在一起了。
我尝试使用
ConstraintLayout,以便使用app:layout_constraintVertical_chainStyle="packed"将视图链接在一起,并且底部(TextView)将具有app:layout_constraintHeight_min="wrap"。也没用。
问题
有没有简单的方法来克服它?要在中心显示两个视图,但优先于 TextView ?
目前,唯一接近可行的解决方案是 2 半解决方案。
【问题讨论】:
-
将横向布局添加到您的activity_main.xml 的布局文件夹中。只需转到设计视图,然后单击设计视图右上角看起来像旋转屏幕图标的按钮 > 创建横向变化。 Android Studio 将自己创建新布局,只需根据需要重新设计即可。
-
问题不在于横向。 Landscape 用于演示两个 View 都没有足够空间的问题。我可以有一个不同的图像,这对于纵向和横向都有问题,或者在小屏幕设备上尝试。
标签: android android-layout android-linearlayout android-constraintlayout