Android中竖线随内容高度变化而变化的问题和解决办法

项目中要求显示竖线,并且竖线高度不确定,竖线的高度要随着内容的变化而变化。不能使用match_parent 充满,也不能在布局中写死,此时使用

android:layout_height="wrap_content"

将不起作用,反而会充满整个屏幕。我在网上搜索了一番,关于这个问题只找到了这样一篇文章 https://blog.csdn.net/gufengpiaoyi/article/details/50129355 ,但是并没有解决实际遇到的问题。经过几天之后想到了一个办法解决了使用<View>作竖线高度动态变化的问题。

解决办法:在竖线的外层套一个父布局RelativeLayout,并且随竖线一起变化的组件同样嵌套在RelativeLayout中,这是最关键的一步。将竖线<View>任意赋值,然后利用相对布局的特性layout_alignBottomlayout_alignTop 来强行设定竖线的上限和下限,这样就解决了高度动态变化的问题。具体使用的实例如下。

1、静态:XML中使用

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout
        android:id="@+id/total_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorWhite">

        <View
            android:id="@+id/verticaline"
            android:layout_width="1dp"
            android:layout_height="@dimen/y10"
            android:layout_marginLeft="@dimen/x38"
            android:layout_alignBottom="@+id/web"
            android:layout_alignParentTop="true"
            android:background="@color/colorDivide"/>

            <TextView
                android:id="@+id/tv_conversationContent"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/x72"
                android:layout_marginTop="@dimen/y24"
                android:layout_marginRight="@dimen/x88"
                android:textColor="#464646"
                android:textSize="@dimen/y38" />

            <WebView
                android:id="@+id/web"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content
                android:layout_below="@+id/tv_conversationContent"
                android:layout_marginRight="@dimen/x88"
                android:layout_marginLeft="@dimen/x60"
                android:layout_marginTop="@dimen/y24" />
        
    </RelativeLayout>
</layout>

上面的布局是Recyclerview的item的布局,在布局中id为verticaline 的View是要显示的竖线,TextViewWebView负责显示从服务器获取的数据,数据内容、高度不确定。这里要求竖线的高度随着TextViewWebView的内容高度变化而变化。所以这里竖线设置的下限是WebView底部,通过layout_alignParentTop的方式让竖线的上限直接置顶。具体请看上述布局中斜体加粗部分。

2、java代码中动态设置

 RelativeLayout.LayoutParams layoutParams= (RelativeLayout.LayoutParams) binding.verticaline.getLayoutParams();
 layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM,binding.web.getId());

其中binding.web代表这上面xml中的WebView,binding.verticaline代表上面xml中的竖线View。通过这样一个办法的设置就限定了竖线高度View的下限是web为底,与上面xml中竖线的效果相同。同理,通过这样的代码还可以设定竖线高度的上限,具体请参照addRule的方法,这个在网上很容易就能查到。

结束语:网上关于View竖线高度问题解决的方式少之又少。希望这个方法能够帮助到您,有什么疑问可以在下面的评论区留言,我能及时看到。但是如果您是几年后看到的这篇文章,那我就不能确保能够及时回复了。

原文地址:https://www.cnblogs.com/1925yiyi/p/9760056.html