Android自定义控件的重要性就不多说了,总之是技术进阶,面试常见,高薪必备。
本篇博文的目的很简单,就是希望通过自定义控件来解决一个常见需求点,从而感受一下自定义控件的魅力与强大。
案例描述:
有一张正方形图片,希望在屏幕上还以正方形,并且不会出现变形,与此同时,希望图片的宽正好是屏幕的宽。
案例效果:
案例实现:
方式一: 使用ImageView来显示图片
方式二:使用自定义控件来显示图片
package com.kedi.mylayout;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
public class MyImageView extends ImageView{
}
package com.kedi.mylayout;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class MyImageView extends ImageView {
public MyImageView(Context context) {
this(context,null);
}
public MyImageView(Context context, AttributeSet attrs) {
this(context,attrs,0);
}
public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs,defStyleAttr);
}
}
(3)实现自定义控件要解决的问题:
package com.kedi.mylayout;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MyImageView extends ImageView{
public MyImageView(Context context) {
this(context,null);
}
public MyImageView(Context context, AttributeSet attrs) {
this(context,attrs,0);
}
public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs,defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
package com.kedi.mylayout;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.RelativeLayout;
/**
* 自定义控件
* @author 张科勇
*
*/
public class MyImageView extends RelativeLayout {
public MyImageView(Context context) {
this(context,null);
}
public MyImageView(Context context, AttributeSet attrs) {
this(context,attrs,0);
}
public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs,defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
<span style="color:#ff0000;"> //获取父布局推荐的宽高,并把小者作为自定义控件的宽高
int width = Math.min(getMeasuredWidth(), getMeasuredHeight());
//将自定义控件的宽高设置成父布局推荐的宽
setMeasuredDimension(width, width);</span>
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<span style="color:#ff0000;"><com.kedi.mylayout.MyImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:background="@drawable/pic" >
</com.kedi.mylayout.MyImageView></span>
</RelativeLayout>
1374



被折叠的 条评论
为什么被折叠?



