Android UI 之一步步教你自定义控件(自定义属性、合理设计onMeasure、合理设计onDraw等)

Unity零基础到进阶 | Unity 探针系统深度解析:光照探针、反射探针与相关技术 在 Unity 渲染管线中,探针(Probe) 是一类通过预计算或实时采样来捕捉空间光照信息的核心组件。它们弥补了传统静态光照贴图和实时光源各自的局限性,是实现高质量、高性能全局光照效果的关键工具。 本文将系统介绍光照探针(Light Probe)和反射探针(Reflection Probe)的作用与用法,分析二者之间的协同关系,并延伸介绍自适应探针体积(APV)、光照探针代理体(LPPV)、探针体积等进阶技术。 阅读详情

    Android开发做到了一定程度,多少都会用到自定义控件,一方面是更加灵活,另一方面在大数据量的情况下自定义控件的效率比写布局文件更高。

    一个相对完善的自定义控件在布局文件中和java代码中都应能灵活设置属性。另外在普通的布局中和AdapterView中都应能正确绘制,这就要求合理设计onMeasure方法,下文中会做比较详细的讲解。

    本文原创,如需转载,请注明转载地址:http://blog.csdn.net/carrey1989/article/details/11757409

    接下来我就一步一步来讲解如何设计和编写一个比较完善的自定义控件。

    首先要来设计好我们要完成的效果,我们今天来实现下图所示的这样一个控件:


    用文字来描述一下:我们要定义的控件上方会显示一张图片,我们可以设置这张图片的内容,长宽比,透明度,伸缩模式,以及图片四周的填充空间大小。图片下方会显示一行文字,作为一级标题,我们可以设置文字的内容,大小,颜色,以及文字区域四周的填充空间的大小。一级标题下方显示一行二级标题,具体设置内容和一级标题相同。

    我们不妨先来直接看一下完成后的效果,这样可以更直观的了解要实现的控件的样子。

                   

    左图的样子是在常规的布局中自定义控件的样子,右图则是在大数据量的情况下自定义控件作为AdapterView的item的时候绘制出来的样子。

    上面我们大体完成了初步的控件设计,下面我们开始编写代码。


    第一步,我们写好自定义属性,根据我们上面所做的设计,我们的自定义属性涉及到三个方面,分别是图片相关的属性,一级标题相关的属性,二级标题相关的属性。

    按照惯例,我们首先在res/values文件目录下创建一个attrs.xml文件。

    然后我们在attrs.xml文件中完成我们对属性的定义,代码片段如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="imageSrc" format="reference"/>
    <attr name="imageAspectRatio" format="float"/>
    <attr name="imageAlpha" format="float"/>
    <attr name="imagePaddingLeft" format="dimension"/>
    <attr name="imagePaddingTop" format="dimension"/>
    <attr name="imagePaddingRight" format="dimension"/>
    <attr name="imagePaddingBottom" format="dimension"/>
    <attr name="imageScaleType">
        <enum name="fillXY" value="0"/>
        <enum name="center" value="1"/>
    </attr>
    
    <attr name="titleText" format="string"/>
    <attr name="titleTextSize" format="dimension"/>
    <attr name="titleTextColor" format="color"/>
    <attr name="titlePaddingLeft" format="dimension"/>
    <attr name="titlePaddingTop" format="dimension"/>
    <attr name="titlePaddingRight" format="dimension"/>
    <attr name="titlePaddingBottom" format="dimension"/>
    
    <attr name="subTitleText" format="string"/>
    <attr name="subTitleTextSize" format="dimension"/>
    <attr name="subTitleTextColor" format="color"/>
    <attr name="subTitlePaddingLeft" format="dimension"/>
    <attr name="subTitlePaddingTop" format="dimension"/>
    <attr name="subTitlePaddingRight" format="dimension"/>
    <attr name="subTitlePaddingBottom" format="dimension"/>
    
    <declare-styleable name="CustomView">
        <attr name="imageSrc"/>
        <attr name="imageAspectRatio" />
        <attr name="imageAlpha" />
        <attr name="imagePaddingLeft" />
        <attr name="imagePaddingTop" />
        <attr name="imagePaddingRight" />
        <attr name="imagePaddingBottom" />
        <attr name="imageScaleType" />
        <attr name="titleText" />
        <attr name="titleTextSize" />
        <attr name="titleTextColor" />
        <attr name="titlePaddingLeft" />
        <attr name="titlePaddingTop" />
        <attr name="titlePaddingRight" />
        <attr name="titlePaddingBottom" />
        <attr name="subTitleText" />
        <attr name="subTitleTextSize" />
        <attr name="subTitleTextColor" />
        <attr name="subTitlePaddingLeft" />
        <attr name="subTitlePaddingTop" />
        <attr name="subTitlePaddingRight" />
        <attr name="subTitlePaddingBottom" />
    </declare-styleable>
</resources>
    这里需要说明几点:<attr>标签的format属性值代表属性的类型,这个类型值一共有10种,分别是:reference,float,color,dimension,boolean,string,enum,integer,fraction,flag

。但是我们作为开发者常用的基本上只有reference,float,color,dimension,boolean,string,enum这7种。在attrs.xml文件中的<declare-styleable>标签的name属性的值,按照惯例我们都是写成自定义控件类的名字。一个同名的<attr>在attrs.xml中只可以定义一次。

    除此之外,上面的代码都是针对前面的设计来定义了各种属性,相信各位同学都能看懂。


    第二步就是编写我们自定义控件的java类了,我们首先将之前做的自定义属性在自定义控件类中做好声明:

	/** 图片Bitmap */
	private Bitmap imageBitmap;
	/** 图片的长宽比 */
	private float imageAspectRatio;
	/** 图片的透明度 */
	private float imageAlpha;
	/** 图片的左padding*/
	private int imagePaddingLeft;
	/** 图片的上padding */
	private int imagePaddingTop;
	/** 图片的右padding */
	private int imagePaddingRight;
	/** 图片的下padding */
	private int imagePaddingBottom;
	/** 图片伸缩模式 */
	private int imageScaleType;
	/** 图片伸缩模式常量 fillXY */
	private static final int SCALE_TYPE_FILLXY = 0;
	/** 图片伸缩模式常量 center */
	private static final int SCALE_TYPE_CENTER = 1;
	
	/** 标题文本内容 */
	private String titleText;
	/** 标题文本字体大小 */
	private int titleTextSize;
	/** 标题文本字体颜色 */
	private int titleTextColor;
	/** 标题文本区域左padding */
	private int titlePaddingLeft;
	/** 标题文本区域上padding */
	private int titlePaddingTop;
	/** 标题文本区域右padding */
	private int titlePaddingRight;
	/** 标题文本区域下padding */
	private int titlePaddingBottom;
	
	/** 子标题文本内容 */
	private String subTitleText;
	/** 子标题文本字体大小 */
	private int subTitleTextSize;
	/** 子标题文本字体颜色 */
	private int subTitleTextColor;
	/** 子标题文本区域左padding */
	private int subTitlePaddingLeft;
	/** 子标题文本区域上padding */
	private int subTitlePaddingTop;
	/** 子标题文本区域右padding */
	private int subTitlePaddingRight;
	/** 子标题文本区域下padding */
	private int subTitlePaddingBottom;
	
	/** 控件用的paint */
	private Paint paint;
	private TextPaint textPaint;
	/** 用来界定控件中不同部分的绘制区域 */
	private Rect rect;
	/** 宽度和高度的最小值 */
	private static final int MIN_SIZE = 12;
	/** 控件的宽度 */
	private int mViewWidth;
	/** 控件的高度 */
	private int mViewHeight;
    然后我们要在构造方法中,将从布局文件中读取的自定义属性解析出来。

		TypedArray a = context.getTheme().obtainStyledAttributes(
				attrs, R.styleable.CustomView, defStyle, 0);
		int n = a.getIndexCount();
		for (int i = 0; i < n; i++) {
			int attr = a.getIndex(i);
			switch (attr) {
			case R.styleable.CustomView_imageSrc:
				imageBitmap = BitmapFactory.decodeResource(
						getResources(), a.getResourceId(attr, 0));
				break;
			case R.styleable.CustomView_imageAspectRatio:
				imageAspectRatio = a.getFloat(attr, 1.0f);//默认长宽相等
				break;
			case R.styleable.CustomView_imageAlpha:
				imageAlpha = a.getFloat(attr, 1.0f);//默认不透明
				if (imageAlpha > 1.0f) imageAlpha = 1.0f;
				if (imageAlpha < 0.0f) imageAlpha = 0.0f;
				break;
			case R.styleable.CustomView_imagePaddingLeft:
				imagePaddingLeft = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_imagePaddingTop:
				imagePaddingTop = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_imagePaddingRight:
				imagePaddingRight = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_imagePaddingBottom:
				imagePaddingBottom = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_imageScaleType:
				imageScaleType = a.getInt(attr, 0);
				break;
			case R.styleable.CustomView_titleText:
				titleText = a.getString(attr);
				break;
			case R.styleable.CustomView_titleTextSize:
				titleTextSize = a.getDimensionPixelSize(
						attr, (int) TypedValue.applyDimension(
								TypedValue.COMPLEX_UNIT_SP, 25, getResources().getDisplayMetrics()));//默认标题字体大小25sp
				break;
			case R.styleable.CustomView_titleTextColor:
				titleTextColor = a.getColor(attr, 0x00000000);//默认黑色字体
				break;
			case R.styleable.CustomView_titlePaddingLeft:
				titlePaddingLeft = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_titlePaddingTop:
				titlePaddingTop = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_titlePaddingRight:
				titlePaddingRight = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_titlePaddingBottom:
				titlePaddingBottom = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_subTitleText:
				subTitleText = a.getString(attr);
				break;
			case R.styleable.CustomView_subTitleTextSize:
				subTitleTextSize = a.getDimensionPixelSize(attr, 
						(int) TypedValue.applyDimension(
								20, TypedValue.COMPLEX_UNIT_SP, getResources().getDisplayMetrics()));//默认子标题字体大小20sp
				break;
			case R.styleable.CustomView_subTitleTextColor:
				subTitleTextColor = a.getColor(attr, 0x00000000);
				break;
			case R.styleable.CustomView_subTitlePaddingLeft:
				subTitlePaddingLeft = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_subTitlePaddingTop:
				subTitlePaddingTop = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_subTitlePaddingRight:
				subTitlePaddingRight = a.getDimensionPixelSize(attr, 0);
				break;
			case R.styleable.CustomView_subTitlePaddingBottom:
				subTitlePaddingBottom = a.getDimensionPixelSize(attr, 0);
				break;
			}
		}
		a.recycle();

    这里需要说明几点,TypedArray对象在使用完毕后一定要调用recycle()方法。我之前曾在一篇文章中总结过在java代码中进行px与dip(dp)、px与sp单位值的转换。实际上,android中也提供了单位转换的函数,我们也可以使用TypedValue.applyDimension(int unit, float value, DisplayMetrics metrics)方法来进行单位的互换,其中,第一个参数是你想要得到的单位,第二个参数是你想得到的单位的数值,比如:我要得到一个25sp,那么我就用TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 25,getResources().getDisplayMetrics()),返回的就是25sp对应的px数值了。


    接下来我们要开始设计onMeasure方法,再设计onMeasure之前我们简单了解几个概念。

    MeasureSpec的三种模式:

    EXACTLY:表示我们设置了MATCH_PARENT或者一个准确的数值,含义是父布局要给子布局一个确切的大小。

    AT_MOST:表示子布局将被限制在一个最大值之内,通常是子布局设置了wrap_content。

    UNSPECIFIED:表示子布局想要多大就可以要多大,通常出现在AdapterView中item的heightMode中。

    了解了上面几个概念,我们就可以开始设计onMeasure了,具体代码如下:

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int widthSize = MeasureSpec.getSize(widthMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		int heightSize = MeasureSpec.getSize(heightMeasureSpec);
		
		int width;
		int height;
		
		if (widthMode == MeasureSpec.EXACTLY) {
			width = widthSize;
		} else {
			int desired = getPaddingLeft() + getPaddingRight() + 
					imagePaddingLeft + imagePaddingRight;
			desired += (imageBitmap != null) ? imageBitmap.getWidth() : 0;
			width = Math.max(MIN_SIZE, desired);
			if (widthMode == MeasureSpec.AT_MOST) {
				width = Math.min(desired, widthSize);
			}
		}
		
		if (heightMode == MeasureSpec.EXACTLY) {
			height = heightSize;
		} else {
			int rawWidth = width - getPaddingLeft() - getPaddingRight();
			int desired = (int) (getPaddingTop() + getPaddingBottom() + imageAspectRatio * rawWidth);
			
			if (titleText != null) {
				paint.setTextSize(titleTextSize);
				FontMetrics fm = paint.getFontMetrics();
				int textHeight = (int) Math.ceil(fm.descent - fm.ascent);
				desired += (textHeight + titlePaddingTop + titlePaddingBottom);
			}
			
			if (subTitleText != null) {
				paint.setTextSize(subTitleTextSize);
				FontMetrics fm = paint.getFontMetrics();
				int textHeight = (int) Math.ceil(fm.descent - fm.ascent);
				desired += (textHeight + subTitlePaddingTop + subTitlePaddingBottom);
			}
			
			height = Math.max(MIN_SIZE, desired);
			if (heightMode == MeasureSpec.AT_MOST) {
				height = Math.min(desired, heightSize);
			}
		}
		
		setMeasuredDimension(width, height);
	}

    思路是这样的:我们首先判断是不是EXACTLY模式,如果是,那就可以直接设置值了,如果不是,我们先按照UNSPECIFIED模式处理,让子布局得到自己想要的最大值,然后判断是否是AT_MOST模式,来做最后的限制。


    完成onMeasure过程之后,我们需要开始onDraw的设计,在onDraw中我们需要考虑各个部分设置的padding值,然后对应做出坐标的处理,整体的思路是从下向上绘制。具体的代码如下:

	@Override
	protected void onDraw(Canvas canvas) {
		rect.left = getPaddingLeft();
		rect.top = getPaddingTop();
		rect.right = mViewWidth - getPaddingRight();
		rect.bottom = mViewHeight - getPaddingBottom();
		
		paint.setAlpha(255);
		if (subTitleText != null) {
			paint.setTextSize(subTitleTextSize);
			paint.setColor(subTitleTextColor);
			paint.setTextAlign(Paint.Align.LEFT);
			
			FontMetrics fm = paint.getFontMetrics();
			int textHeight = (int) Math.ceil(fm.descent - fm.ascent);
			
			int left = getPaddingLeft() + subTitlePaddingLeft;
			int right = mViewWidth - getPaddingRight() - subTitlePaddingRight;
			int bottom = mViewHeight - getPaddingBottom() - subTitlePaddingBottom;
			
			String msg = TextUtils.ellipsize(subTitleText, textPaint, right - left, TextUtils.TruncateAt.END).toString();
			
			float textWidth = paint.measureText(msg);
			float x = textWidth < (right - left) ? left + (right - left - textWidth) / 2 : left;
			canvas.drawText(msg, x, bottom - fm.descent, paint);
			
			rect.bottom -= (textHeight + subTitlePaddingTop + subTitlePaddingBottom);
		}
		
		if (titleText != null) {
			paint.setTextSize(titleTextSize);
			paint.setColor(titleTextColor);
			paint.setTextAlign(Paint.Align.LEFT);
			
			FontMetrics fm = paint.getFontMetrics();
			int textHeight = (int) Math.ceil(fm.descent - fm.ascent);
			
			float left = getPaddingLeft() + titlePaddingLeft;
			float right = mViewWidth - getPaddingRight() - titlePaddingRight;
			float bottom = rect.bottom - titlePaddingBottom;
			
			String msg = TextUtils.ellipsize(titleText, textPaint, right - left, TextUtils.TruncateAt.END).toString();
			
			float textWidth = paint.measureText(msg);
			float x = textWidth < right - left ? left + (right - left - textWidth) / 2 : left;
			canvas.drawText(msg, x, bottom - fm.descent, paint);
			
			rect.bottom -= (textHeight + titlePaddingTop + titlePaddingBottom);
		}
		
		if (imageBitmap != null) {
			paint.setAlpha((int) (255 * imageAlpha));
			rect.left += imagePaddingLeft;
			rect.top += imagePaddingTop;
			rect.right -= imagePaddingRight;
			rect.bottom -= imagePaddingBottom;
			if (imageScaleType == SCALE_TYPE_FILLXY) {
				canvas.drawBitmap(imageBitmap, null, rect, paint);
			} else if (imageScaleType == SCALE_TYPE_CENTER) {
				int bw = imageBitmap.getWidth();
				int bh = imageBitmap.getHeight();
				if (bw < rect.right - rect.left) {
					int delta = (rect.right - rect.left - bw) / 2;
					rect.left += delta;
					rect.right -= delta;
				}
				if (bh < rect.bottom - rect.top) {
					int delta = (rect.bottom - rect.top - bh) / 2;
					rect.top += delta;
					rect.bottom -= delta;
				}
				canvas.drawBitmap(imageBitmap, null, rect, paint);
			}
		}
	}

    当做完这一步的时候,我们的自定义控件已经能够在布局文件中进行使用了,但是我们还不能在AdapterView中用我们设计的布局文件,因为AdapterView中每一个item属性都是在java代码中动态设置的,因此我们就需要给我们的自定义控件开放属性设置的接口,我们这里暂时只开放了设置图片和文字内容的接口。

	public void setImageBitmap(Bitmap bitmap) {
		imageBitmap = bitmap;
		requestLayout();
		invalidate();
	}
	
	public void setTitleText(String text) {
		titleText = text;
		requestLayout();
		invalidate();
	}
	
	public void setSubTitleText(String text) {
		subTitleText = text;
		requestLayout();
		invalidate();
	}

    做到这一步的时候,这个自定义控件基本就算完成了,后续的工作就是一些完善和修补了。

    接下来就是自定义控件的使用了,在布局文件中使用自定义控件的时候我们需要额外做一点工作,如下:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:carrey="http://schemas.android.com/apk/res/com.carrey.customview"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <com.carrey.customview.customview.CustomView 
        android:id="@+id/customview"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerInParent="true"
        android:background="#FFD700"
        carrey:imageSrc="@drawable/clock"
        carrey:imageAspectRatio="1.0"
        carrey:imageAlpha="0.5"
        carrey:imagePaddingLeft="5dp"
        carrey:imagePaddingTop="5dp"
        carrey:imagePaddingRight="5dp"
        carrey:imagePaddingBottom="5dp"
        carrey:imageScaleType="center"
        carrey:titleText="这是一级标题"
        carrey:titleTextSize="30sp"
        carrey:titleTextColor="#1E90FF"
        carrey:titlePaddingLeft="4dp"
        carrey:titlePaddingTop="4dp"
        carrey:titlePaddingRight="4dp"
        carrey:titlePaddingBottom="4dp"
        carrey:subTitleText="这是二级子标题"
        carrey:subTitleTextSize="20sp"
        carrey:subTitleTextColor="#00FF7F"
        carrey:subTitlePaddingLeft="3dp"
        carrey:subTitlePaddingTop="3dp"
        carrey:subTitlePaddingRight="3dp"
        carrey:subTitlePaddingBottom="3dp"/>

    <Button 
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="next page"/>
</RelativeLayout>
我们需要添加一行xmlns:carrey="http://schemas.android.com/apk/res/com.carrey.customview",其中carrey是一个前缀,你可以随意设置,com.carrey.customview是我们的应用的包名,如果拿不准的可以打开Manifest文件,在<manifest>节点中找到package属性值即可。
对于在AdapterView中的使用方法就和我们正常使用一个常用控件的方法是一样的,这里就不赘述了,如果说到了这里还有一些不明白的地方,可以下载我下面提供的源码,然后对照着博客的思路来看,或者给我留言进行交流。

源码下载



YOLOv11 改进 - 检测头 | Detect_LSCD轻量共享卷积检测头:轻量化设计破解计算瓶颈,增强复杂场景目标感知能力 本文介绍了基于群归一化(GroupNorm)和共享卷积的轻量化检测头LSCD,并将其集成进YOLOv11。LSCD检测头充分利用了GroupNorm和共享卷积的优势,在保持特征信息有效融合的同时,减少计算量和运算复杂度。我们将LSCD的代码集成到YOLOv11检测头中,并在tasks文件中进行注册。实验证明,YOLOv11-LSCD在目标检测任务中取得了良好的效果。 阅读详情

相关推荐

从CPU视角看PCIe:深入理解x86/ARM平台上BAR、MMIO和PIO的地址翻译与访问机制

本文深入探讨了CPU如何通过BAR、MMIO和PIO机制访问PCIe设备的配置空间,详细解析了x86和ARM平台在地址翻译与访问路径上的差异。重点分析了PCIe配置空间中BAR寄存器的作用与探测机制,以及操作系统如何管理PCIe资源,为开发者提供了性能优化与调试的实用技巧。

weixin_30175731的博客 331

android自定义控件用xml赋值,Android自定义组件,并把自定义组件和自定义xml布局文件关联...

前言在开发自定义view时,往往需要绑定xml布局文件,那具体怎么做呢?自定义view和xml布局文件关联的思路是:在自定义view的构造函数中,通过LayoutInflater.from(context).inflate(R.layout.test_layout, this)关联xml布局文件。具体代码如下1、代码自定义布局——xml代码(test_layout.xml)android:layo...

weixin_33224795的博客 662

ROS四旋翼无人机快速上手指南(3):工作环境文件框架与各功能包整体讲解

这一章节主要讲解无人机平台的控制文件架构和各个功能包组成和用法。

The Road of Engineer 2411

android 自定义控件

View的原理介绍View表示的的屏幕上的某一块矩形的区域,而且所有的View都是矩形的;如同简介中介绍,View是不能添加子View的,而ViewGroup是可以添加子View的。ViewGroup之所以能够添加子View,是因为它实现了两个接口:ViewParent 和 ViewManager;Activity之所以能加载并且控制View,是因为它包含了一个Window,所有的图形化界面都是由...

weixin_41205419的博客 348

STM32-printf重定向串口输出

声明 本文内容转载至https://www.mculover666.cn/posts/2251182441/ 1.printf与fputc printf 定义在 <stdio.h> 头文件中,如下: int printf(const char *format, ...); printf 函数根据 format 字符串给出的格式打印输出到 stdout(标准输出)中,当然,printf 函数是不会一个字符一个字符去输出,它会调用更底层的 I/O 函数:fputc去逐个字符打印。 fputc 也定

qq_41215167的博客 4547

用COMSOL计算复合材料板频散曲线:从建模到绘图全流程

导波在板结构中传播时,不同频率成分的速度不同,即频散现象。理解频散曲线是识别导波模态、确定相速度与群速度的基础,也是无损检测和结构健康监测中信号解读的关键。对于碳纤维增强复合材料等各向异性板,频散关系更加复杂,传统解析方法难以求解,数值仿真成为主流手段。通过COMSOL结合周期性边界条件与特征频率扫描,可以高效计算出复合材料板的频散曲线,进而绘制相速度和群速度随频率变化的图谱,为实验模态识别、换能器激励频率选择提供依据。本文以一个2毫米单向碳纤维板为例,详细介绍几何建模、材料参数设置、网格收敛验证、参数扫描

weixin_31412781的博客 245

Android 自定义titlebar控件(自定义UI控件)

1、创建自定义的属性: 2、在自定义的布局中获取属性; 3、在mainActivity中使用 自定义控件,并使用自定义属性赋值。 1、创建自定义的属性创建 values/attr.xml 文件; &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;declare-styleable name...

zhanglinlang的专栏 2373

避坑指南:SpringBoot对接拉卡拉支付常见问题与解决方案(含SDK 1.0.6配置技巧)

本文是一份SpringBoot项目对接拉卡拉支付的实战避坑指南。针对SDK 1.0.6版本,详细剖析了从依赖管理、多环境配置、SDK初始化到支付请求构建、回调验签及生产监控的全流程常见问题,并提供了经过验证的解决方案与配置技巧,旨在帮助开发者高效、稳定地集成支付功能。

k5l6m的博客 344

Android 自定义view 入门 案例

9.最后在新建一个页面:ThreeActivity, 并在AndroidManifest.xml,设置为启动页面。创建完成后,在xml添加自定义view:activity_three.xml。第一个是逻辑代码,第二个是布局,第三个是view需要使用的属性(通过这种方式创建属性,多次创建可能造成一些变量重复定义。8.更新自定义布局:sample_super_circle_view.xml。sample_super_circle_view.xml布局源码。3.输入自定义名称,选择开发语言。11.最后运行即可。

LlanyW的专栏 1225

GD32E230G8U6TR串口接收超时中断、帧中断配置使用笔记

项目场景: MCU-GD32E230G8U6TR: 最近项目需求需要使用GD32E230G8U6TR这款MCU开发MODBUS通信,modbus开发需要使用帧中断功能,而网上GD32关于这一块的内容资料不是很多,兆易官网也没找到合适的例程,没办法只能自己照着手册折腾了好久。 解决方案: 提示 根据用户手册的介绍来看,串口中断功能中自带接收超时中断功能,使用过程先调用usart_receiver_timeout_threshold_config(USARTX,timerout)函数设置超时时间阈值,这里t

wojiusuibiankan的博客 5265

RL调参侠之BipedalWalker BipedalWalkerHardcore SAC

前几天用PPO训练了个很一般的agent: RL调参侠之BipedalWalker PPO 我看SpinningUp上面说PPO和SAC是两个领域里各自的State_of_the_art的方法,所以就打算跑SAC试试看,之前因为Open AI Five的原因,一直感觉PPO很牛掰,实际上现在很多自动驾驶的算法也是用PPO在跑,毕竟有一个“必定能够提升期望”的理论保证在这里,我理解这对做项目很大的诱惑。 不过我跑出来的结果明显是SAC更好。 调参侠时间 策略熵的权重alpha用的0.2,我一开始没有看SAC的

weixin_48370148的博客 2108

安卓创建自定义控件

引入布局的技巧确实解决了重复编写布局代码的问题,但是如果布局中有一些控件要求能够响应事件,我们还是需要在每个活动中为这些控件单独编写一次事件注册的代码。我们可通过如下方式解决}}

weixin_57244464的博客 1198

SAP Group Reporting入门指南(8)--业务操作

关于资产负债表类的匹配,系统预设了SGR01和SGR02两个方法,主要区别在于数据的来源范围,SGR01取自ACDOCA和ACDOCU,如果是0F类型的就会直接显示日记账分录(期间是000的除外,这类凭证是年结结转的,系统不再跨年追溯),如果是其他类型就显示合并分录。这里是我觉得SAP还需要优化的地方。基于ICMR的抵消任务中通常将抵销差异细分为交易差异、货币换算差异和其他差异,这在基于重分类抵消任务是无法实现的,基于重分类抵消只知道一个差异总额,很难从合并抵消凭证看出差异的来源,也没有审计线索可言。

bflyfish的博客 285

【Android 界面效果15】Android UI 之一步步教你自定义控件(自定义属性、合理设计onMeasure、合理设计onDraw等)

Android开发做到了一定程度,多少都会用到自定义控件,一方面是更加灵活,另一方面在大数据量的情况下自定义控件的效率比写布局文件更高。     一个相对完善的自定义控件在布局文件中和java代码中都应能灵活设置属性。另外在普通的布局中和AdapterView中都应能正确绘制,这就要求合理设计onMeasure方法,下文中会做比较详细的讲解。     本文原创,如需转载,请注明转载地址:htt

Geek马走日 509

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Android UI 之一步步教你自定义控件(自定义属性、合理设计onMeasure、合理设计onDraw等)...

Android开发做到了一定程度,多少都会用到自定义控件,一方面是更加灵活,另一方面在大数据量的情况下自定义控件的效率比写布局文件更高。 一个相对完善的自定义控件在布局文件中和java代码中都应能灵活设置属性。另外在普通的布局中和AdapterView中都应能正确绘制,这就要求合理设计onMeasure方法,下文中会做比较详细的讲解。 本文原创,如需转载,请注明转载地址...

weixin_30558305的博客 83

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

【Android 界面效果15】Android UI 之一步步教你自定义控件(自定义属性、合理设计onMeasure、合理设计onDraw等)...

Android开发做到了一定程度,多少都会用到自定义控件,一方面是更加灵活,另一方面在大数据量的情况下自定义控件的效率比写布局文件更高。 一个相对完善的自定义控件在布局文件中和java代码中都应能灵活设置属性。另外在普通的布局中和AdapterView中都应能正确绘制,这就要求合理设计onMeasure方法,下文中会做比较详细的讲解。 本文原创,如需转载,请注明转载地址...

weixin_30336061的博客 73

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Android UI 之一步步教你自定义控件

本文章转自安卓巴士 http://www.apkbus.com/forum.php?mod=viewthread&tid=141745 网上看到很多有关自定义控件的文章,有很大一部分文章就是简单的把图片和文字混合在一起而已,并没有去给控件自定义属性。这样简单的在布局文件里就可以实现,还用你去费那个劲?而且那些文章起不到好的效果,反而会将别人带沟里,误人子弟。好了,吐槽完了,下面看正文。

a1010012805的博客 921

【Android源码】Android UI 之一步步教你自定义控件

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33720452的博客 157
上一篇: Android UI 之WaterFall瀑布流效果
下一篇: Java 基本功 之中断线程的理解
如毛毛风
博客等级 码龄15年 193粉丝 11原创
评论 21
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值