位置: 编程技术 - 正文

Android 自定义组件之如何实现自定义组件(android自定义组件开发详解)

编辑:rootadmin

推荐整理分享Android 自定义组件之如何实现自定义组件(android自定义组件开发详解),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:android自定义组件开发详解,android自定义列表,android自定义组件开发详解,Android自定义组件性能,android自定义列表,android自定义组件,android自定义组件开发详解,Android自定义组件性能,内容如对您有帮助,希望把文章链接给更多的朋友!

原文地址: TextView, EditText, ListView, CheckBox,RadioButton, Gallery, Spinner,以及一些有特别作用的组件: AutoCompleteTextView, ImageSwitcher和 TextSwitcher。

可用的布局有:LinearLayout,FrameLayout,RelativeLayout,AbsoluteLayout,GridLayout (later on api level or v7-support)

基本做法

1. 继承自View或View的子类

2. 重写父类的一些方法,如:onDraw(),onMeasure(),onLayout()等

3. 使用自定义的组件类。

完全自定义组件1. 最普通的作法是,继承自View,实现你的自定义组件

2. 提供一个构造函数,采用有属性参数的,也可以使用自定义属性

3. 你可能想在组件中创建自己的事件监听器,属性访问器和修改器,或其他行为

4. 几乎肯定要重写onDraw(),onMeasure()。默认onDraw()什么也没作,onMeasure()则设置一个x的尺寸。

5. 根据需要重写其他方法 ...

onDraw()和onMeasure()

onDraw(),提供一个Canvas,可以绘制2D图形。

若要绘制3D图形,请继承GLSurfaceView,参见,api-demo下的 GLSurfaceViewActivity

Android 自定义组件之如何实现自定义组件(android自定义组件开发详解)

onMeasure() 测量组件

1. 宽度和高度在需要测量时调用该方法

2. 应该进行测量计算组件将需要呈现的宽度和高度。它应该尽量保持传入的规&#;范围内,尽管它可以选择超过它们(在这种情况下,父视图可以选择做什么,包括裁剪,滚动,抛出一个异常,或者要求onMeasure()再次尝试,或使用不同的测量规&#;)

3. 宽高计算完毕后,必须调用用setMeasuredDimession(int width, int height),进行设置。否则将抛出一个异常

下面是一些View中可被调用的方法总结(未全部包含,可自行查看类&#;onXxx的方法):

CategoryMethodsDescriptionCreationConstructorsThere is a form of the constructor that are called when the view is created from code and a form that is called when the view is inflated from a layout file. The second form should parse and apply any attributes defined in the layout file.onFinishInflate()Called after a view and all of its children has been inflated from XML.LayoutonMeasure(int, int)Called to determine the size requirements for this view and all of its children.onLayout(boolean, int, int, int, int)Called when this view should assign a size and position to all of its children.onSizeChanged(int, int, int, int)Called when the size of this view has changed.DrawingonDraw(Canvas)Called when the view should render its content.Event processingonKeyDown(int, KeyEvent)Called when a new key event occurs.onKeyUp(int, KeyEvent)Called when a key up event occurs.onTrackballEvent(MotionEvent)Called when a trackball motion event occurs.onTouchEvent(MotionEvent)Called when a touch screen motion event occurs.FocusonFocusChanged(boolean, int, Rect)Called when the view gains or loses focus.onWindowFocusChanged(boolean)Called when the window containing the view gains or loses focus.AttachingonAttachedToWindow()Called when the view is attached to a window.onDetachedFromWindow()Called when the view is detached from its window.onWindowVisibilityChanged(int)Called when the visibility of the window containing the view has changed.自定义View示例

adi-demo下的示例:LabelView

[java] view plaincopy/* * Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.view.View; /** * Example of how to write a custom subclass of View. LabelView * is used to draw simple text views. Note that it does not handle * styled text or right-to-left writing systems. * */ public class LabelView extends View { /** * Constructor. This version is only needed if you will be instantiating * the object manually (not from a layout XML file). * @param context the application environment */ public LabelView(Context context) { super(context); initLabelView(); } /** * Construct object, initializing with any attributes we understand from a * layout file. These attributes are defined in * SDK/assets/res/any/classes.xml. * * @see android.view.View#View(android.content.Context, android.util.AttributeSet) public LabelView(Context context, AttributeSet attrs) { super(context, attrs); initLabelView(); Resources.StyledAttributes a = context.obtainStyledAttributes(attrs, R.styleable.LabelView); CharSequence s = a.getString(R.styleable.LabelView_text); if (s != null) { setText(s.toString()); } ColorStateList textColor = a.getColorList(R.styleable. LabelView_textColor); if (textColor != null) { setTextColor(textColor.getDefaultColor(0)); } int textSize = a.getInt(R.styleable.LabelView_textSize, 0); if (textSize > 0) { setTextSize(textSize); } a.recycle(); } */ private void initLabelView() { mTextPaint = new Paint(); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(); mTextPaint.setColor(0xFF); mPaddingLeft = 3; mPaddingTop = 3; mPaddingRight = 3; mPaddingBottom = 3; } /** * Sets the text to display in this label * @param text The text to display. This will be drawn as one line. */ public void setText(String text) { mText = text; requestLayout(); invalidate(); } /** * Sets the text size for this label * @param size Font size */ public void setTextSize(int size) { mTextPaint.setTextSize(size); requestLayout(); invalidate(); } /** * Sets the text color for this label * @param color ARGB value for the text */ public void setTextColor(int color) { mTextPaint.setColor(color); invalidate(); } /** * @see android.view.View#measure(int, int) */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } /** * Determines the width of this view * @param measureSpec A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int measureWidth(int measureSpec) { int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text result = (int) mTextPaint.measureText(mText) &#; mPaddingLeft &#; mPaddingRight; if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; } /** * Determines the height of this view * @param measureSpec A measureSpec packed into an int * @return The height of the view, honoring constraints from measureSpec */ private int measureHeight(int measureSpec) { int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); mAscent = (int) mTextPaint.ascent(); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text (beware: ascent is a negative number) result = (int) (-mAscent &#; mTextPaint.descent()) &#; mPaddingTop &#; mPaddingBottom; if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; } /** * Render the text * * @see android.view.View#onDraw(android.graphics.Canvas) */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawText(mText, mPaddingLeft, mPaddingTop - mAscent, mTextPaint); } private Paint mTextPaint; private String mText; private int mAscent; }

应用该自定义组件的layout xml:

[html] view plaincopy<LinearLayout xmlns:android=" xmlns:app=" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <com.example.android.apis.view.LabelView android:background="@drawable/red" android:layout_width="match_parent" android:layout_height="wrap_content" app:text="Red"/> <com.example.android.apis.view.LabelView android:background="@drawable/blue" android:layout_width="match_parent" android:layout_height="wrap_content" app:text="Blue" app:textSize="dp"/> <com.example.android.apis.view.LabelView android:background="@drawable/green" android:layout_width="match_parent" android:layout_height="wrap_content" app:text="Green" app:textColor="#ffffffff" /> </LinearLayout> 该示例演示了:

1. 继承自View的完全自定义组件

2. 带参数的构造函数(一些属性参数在xml中设置)。还使用了自定义属性 R.styleable.LabelView

3. 一些标准的public 方法,如setText()、setTextSize()、setTextColor()

4. onMeasure()测量组件尺寸,内部由measureWidth(int measureSpec) 和 measureHeight(int measureSpec)来测量。

5. onDraw()将Label绘制到画面Canvas上

复合组件由一些现有组件,复合成一个新的组件。要创建一个复合组件:1. 通常需要创建一个类,继承自一个Layout,或者ViewGroup。2. 在构造函数中,需要先调用父类相应的构造函数。然后设置一些需要的组件用于复合。可以使用自定义属性3. 可以创建监听器,监听处理一些可能的动作4. 可能有一些 属性的 get / set 方法5. 如果继承自某一Layout类时,不需要重写onDraw()和onMeasure(),因为Layout类中有默认的行为。如有必要,当然也可以重写6. 可能重写其他一些onXxx(),以达到你想要的效果复合组件示例api-demo下的List4和List6里的内部类SpeachView,以下为List6中的源码[java] view plaincopyprivate class SpeechView extends LinearLayout { public SpeechView(Context context, String title, String dialogue, boolean expanded) { super(context); this.setOrientation(VERTICAL); // Here we build the child views in code. They could also have // been specified in an XML file. mTitle = new TextView(context); mTitle.setText(title); addView(mTitle, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mDialogue = new TextView(context); mDialogue.setText(dialogue); addView(mDialogue, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mDialogue.setVisibility(expanded ? VISIBLE : GONE); } /** * Convenience method to set the title of a SpeechView */ public void setTitle(String title) { mTitle.setText(title); } /** * Convenience method to set the dialogue of a SpeechView */ public void setDialogue(String words) { mDialogue.setText(words); } /** * Convenience method to expand or hide the dialogue */ public void setExpanded(boolean expanded) {//该方法在List4中没有 mDialogue.setVisibility(expanded ? VISIBLE : GONE); } private TextView mTitle; private TextView mDialogue; } SpeachView,继承了LinearLayout,纵向布局。内部有一个TextView的title,一个TextView的dialogue。List4完全展开两个TextView;List6点击title可以收缩/展开dialogue。修改现有View类型继承自一个现有的View,以增强其功能,满足需要。sdk中有个记事本NotePad的示例工程。其中有一个类就是扩展了EditText。在NoteEditor类中:[java] view plaincopypublic static class LinedEditText extends EditText { private Rect mRect; private Paint mPaint; // This constructor is used by LayoutInflater public LinedEditText(Context context, AttributeSet attrs) { super(context, attrs); // Creates a Rect and a Paint object, and sets the style and color of the Paint object. mRect = new Rect(); mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(0xFF); } /** * This is called to draw the LinedEditText object * @param canvas The canvas on which the background is drawn. */ @Override protected void onDraw(Canvas canvas) { // Gets the number of lines of text in the View. int count = getLineCount(); //edittext中有几行, edittext继承textview // Gets the global Rect and Paint objects Rect r = mRect; Paint paint = mPaint; /* * Draws one line in the rectangle for every line of text in the EditText */ for (int i = 0; i < count; i&#;&#;) { // Gets the baseline coordinates for the current line of text int baseline = getLineBounds(i, r);//将一行的范围坐标赋给矩形r;返回一行y方向上的基准线坐标 /* * Draws a line in the background from the left of the rectangle to the right, * at a vertical position one dip below the baseline, using the "paint" object * for details. */ canvas.drawLine(r.left, baseline &#; 1, r.right, baseline &#; 1, paint);//绘制一条线,宽度为原行的宽度,高度为从基线开始&#;1个像素 } // Finishes up by calling the parent method super.onDraw(canvas); } } 定义一个public的静态内部类,以便它可以被访问:NoteEditor.MyEditText它是静态内部类,意味着,它不依靠外部类的成员,不会产生一些“组合的方法”。继承自EditText类的初始化构造函数中,先调用父类的构造方法,并且它是带属性参数的构造函数。在使用时,从一个xml布局文件inflate重写的方法只有onDraw()被重写。在onDraw()中绘制了一条蓝色的线,该线从每行文本的的基线开始向下1像素,宽度为行宽。方法结束前,调用super.onDraw()使用自定义组件[html] view plaincopy<view xmlns:android=" class="com.example.android.notepad.NoteEditor$LinedEditText" android:id="@&#;id/note" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/transparent" android:padding="5dp" android:scrollbars="vertical" android:fadingEdge="vertical" android:gravity="top" android:textSize="sp" android:capitalize="sentences" /> 使用完全限定类名,引入自定义组件。使用$引用内部类。

Android动画探索——图标依次变大的水滴效果 一直打算模仿ios,做一个安卓的水滴效果:比如有四个图标,四个图标依次出现,并由小变大。就像水滴掉落时一头大一头小一样。首先分析需求:1.四

安卓getListView().setTextFilterEnabled(true) getListView().setTextFilterEnabled(true),函数setTextFilterEnabled,属性为true表示listview获得当前焦点的时候,与相应用户输入的匹配符进行比对,筛选出匹配的ListV

通过WIFI连接安卓设备调试 首先在安卓终端下载一个shell程序,我下载的是androidterminalemulator下载完成,安装,运行如下命令:surootsetpropservice.adb.tcp.portstopadbdstartadbd命令完成,可

标签: android自定义组件开发详解

本文链接地址:https://www.jiuchutong.com/biancheng/381030.html 转载请保留说明!

上一篇:JUnit4 多线程执行测试用例(junit 原理)

下一篇:Android动画探索——图标依次变大的水滴效果(android view动画)

  • 税务做定额
  • 会议服务费免税吗
  • 小规模纳税人收到专票后如何处理
  • 个人劳务所得税税率表最新2022
  • 高薪技术企业研发人员人数
  • 公司工资发放错误怎么退回
  • 取消国税用什么手续
  • 商品过期可以向商家索要赔偿吗
  • 现金折扣后退回账户
  • 增值税发票暂时无法查看怎么回事
  • 没签合同怎么交社保
  • 个体户的公账怎么操作
  • 购入生产车间
  • 财务计提个人缴纳社保部分怎么记账?
  • 当月作废的发票是否需要报税
  • 网络不通怎么拼ip
  • 趣谈linux系统
  • 华为鸿蒙系统开发平台
  • 母公司投资子公司怎么做账
  • 通行证普通发票放在凭证哪里
  • 增值税三流合一涉及子公司
  • php生成条形码的代码
  • 汇算清缴补交的所得税怎么记帐
  • 在php中如何对多条记录进行分页
  • [Vue]Vue3学习笔记(尚硅谷)
  • vue2 mixin
  • yolo s
  • pytorch map
  • 企业预付账款怎么做账
  • 发票违法行为的认定
  • 增值税一般纳税人
  • 农产品收购发票可以抵扣进项税额吗
  • C++ lower_bound/upper_bound用法解析
  • 防伪税款服务费抵扣
  • 残保金相关内容有哪些
  • 应付帐款借方余额,但对方公司己注销
  • 人力资源行业企业成长
  • 回购注销库存股的会计处理
  • 委托加工存货收回后直接用于销售的账务处理
  • 运输公司自有车辆是什么意思
  • 做账工资和申报工资不一样有风险吗
  • 质量问题扣货款会计怎么处理
  • 金税盘缴销发票
  • 应收票据贷方余额
  • 如何处理消防安全事件
  • 实收资本小于注册资本账务处理
  • 销售净利润怎么算
  • 工业企业的生产费用包括哪些
  • mysql事件调用存储过程
  • linux虚拟局域网搭建
  • centos如何禁ping
  • 怎么使用winpe
  • 解决mac上不能写字的办法
  • 装win7系统步骤
  • u盘启动安装xp系统教程
  • linux系统叫啥
  • win8系统与win10哪个好
  • windows8中“同步你的设置”使用介绍(让你的设置自动同步)
  • win10快捷键合集
  • win10 mobile 1709
  • win7系统360浏览器收藏夹位置
  • linux 指定动态库连接位置
  • css各种滤镜的应用是什么
  • js实现日历可获得的信息
  • jquery移动div到另一个div中
  • android中的动画有哪几类,它们的特点和区别是什么?
  • unity3d入门视频教程
  • javascript教程chm
  • js中倒计时器怎么实现
  • JavaScript html5 canvas画布中删除一个块区域的方法
  • javascript入门教学
  • 用python写一个程序
  • jquery实现下拉框
  • 如何动态加载外部文件
  • 哪些润滑油属于润滑剂
  • 生鲜肉类免税
  • 农机免税范围
  • 商事登记本
  • 税务局的纳税服务有哪些
  • 吉林省国税局网站官网
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设