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

来源:互联网 发布:淘宝店铺设计 编辑:程序博客网 时间:2024/05/23 19:46

http://blog.csdn.net/qq_33245265/article/details/52600647

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

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

package com.example.myapplication;import android.content.Context;import android.util.AttributeSet;import android.widget.ImageView;/** * Created by my-pc-02 on 2017/6/22. */public class SquareImageView extends ImageView {    public SquareImageView(Context context) {        super(context);    }    public SquareImageView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public SquareImageView(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.SquareImageView            android:layout_width="0dp"            android:layout_height="match_parent"            android:layout_weight="1"            android:background="#FF0000"            android:src="@mipmap/ic_launcher" />        <com.example.myapplication.SquareImageView            android:layout_width="0dp"            android:layout_height="100dp"            android:layout_weight="1"            android:background="#00FF00"            android:src="@mipmap/ic_launcher"/>        <com.example.myapplication.SquareImageView            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
原创粉丝点击