android实现正方形的ImageView、Layout等(即高度适应宽度或者宽度适应高度)

有时候我们希望在一个页面中水平放置若干个正方形的ImageView,其总宽度为整个屏幕。如果我们设定每个ImageView的高度和者宽度均为若干个dp,因为不知道屏幕尺寸,就可能导致显示不全或者有剩余空间。可以通过以下这个方法设定ImageView其为正方形

首先,建立一个类MyImageView继承ImageView类

 

package com.example.myapplication;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by logaxy on 2016/9/20.
 */

public class MyImageView extends ImageView {
    public MyImageView(Context context) {
        super(context);
    }

    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //传入参数widthMeasureSpec、heightMeasureSpec
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}
然后重写onMeasure()方法, 其接受两个参数int widthMeasureSpec, int heightMeasureSpec,
分别为宽度和高度,这时候我们在onMeasure()再次调用super.onMeasure()即可,这时候如果是
super.onMeasure(widthMeasureSpec, widthMeasureSpec);则表示高度和宽度均为宽度值,即高
度适应宽度。如果是super.onMeasure(heightMeasureSpec, heightMeasureSpec);则表示宽度适
应高度;

然后再布局文件中,我们直接使用全路径的MyImageView即可
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.myapplication.MainActivity">
    
        <com.example.myapplication.MyImageView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#FF0000"
            android:src="@mipmap/ic_launcher" />

        <com.example.myapplication.MyImageView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_weight="1"
            android:background="#00FF00"
            android:src="@mipmap/ic_launcher"/>

        <com.example.myapplication.MyImageView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#0000FF"
            android:src="@mipmap/ic_launcher"/>

</LinearLayout>

可以看到在布局文件中有一个LinearLayout,里面有三个水平排列的ImegeView,它们宽度均分LinearLayout,
高度在定义上各不相同,但是其效果如下图所示,是三个正方形,就是说它们的高度是适应宽度的。


如果想要Layout等同样做到正方形效果或者其他特定比例的矩形效果也可以用这个方法,新建一个继承类,
重写onMeasure()方法方法即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值