美文网首页
Android宽度填充屏幕 宽高相等的View

Android宽度填充屏幕 宽高相等的View

作者: 咖啡伴辣条 | 来源:发表于2018-08-27 12:20 被阅读0次

    写一个宽度到边,高度与宽度相等的ImageView怎么实现

    暂时考虑以下几种实现方式:

    1 百分比布局

    PercentRelativeLayout 设置宽度100% 宽高比100%

    <ImageView
                android:id="@+id/imageView"
                app:layout_widthPercent="100%"
                app:layout_aspectRatio="100%"
                app:srcCompat="@mipmap/ic_launcher"
             />
    

    2 ConstraintLayout 约束布局
    设置宽度match_parent 高度0dp 宽高比1:1 两种写法, 如下

     <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintDimensionRatio="1:1"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@mipmap/ic_launcher" />
    
    <TextView
            android:id="@+id/text"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:gravity="center"
            android:text="text"
            app:layout_constraintDimensionRatio="H,1:1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent" />
    

    3 自定义ImgeView 重写onMeasure()方法

    设置宽度match_parent 高度 wrap_content 或0dp ...

     @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, widthMeasureSpec);
        }
    

    4
    通过java代码动态设置ImageView

    PercentRelativeLayout 的属性

    <!--设置相对父控件百分比-->
    app:layout_widthPercent
    app:layout_heightPercent
    
    
    <!--设置控件相对于父控件的边距百分比-->
    app:layout_marginLeftPercent
    app:layout_marginTopPercent
    app:layout_marginRightPercent
    app:layout_marginBottomPercent
    
    <!--距离开始和结束的位置-->
    app:layout_marginStartPercent
    app:layout_marginEndPercent
    
    <!--根据宽或者高按比例设置另一个-->
    android:layout_width="300dp"
    app:layout_aspectRatio 
    

    ConstraintLayout 的属性

    引用别人的文章吧

    相关文章

      网友评论

          本文标题:Android宽度填充屏幕 宽高相等的View

          本文链接:https://www.haomeiwen.com/subject/qfcziftx.html