前言:

自定义View可以分为两种方式:

  • 第一种通过继承ViewGroup,内部通过addView的方式将其他的View组合到一起。
  • 第二种则是通过继承View,重启View的onMeasure,onLayout,onDraw方法来绘制不规则图形,如折线图等。

本文介绍的是第一种方式通过组合的方式去实现自定义View。

实现自定义View首先要自定义属性。对于自定义属性,第一步是在项目res/values文件夹中新建attrs.xml文件,在文件中设置自定义属性的名称和类型,

代码如下:

<resources>
    <declare-styleable name="InputItemLayout">
        <attr name="hint" format="string"></attr>
        <attr name="title" format="string"/>
        <attr name="inputType" format="enum">
            <enum name="text" value="0"/>
            <enum name="password" value="1"/>
            <enum name="number" value="2"/>
        </attr>
        <attr name="inputTextAppearance" format="reference"/>
        <attr name="titleTextAppearance" format="reference"/>
        <attr name="topLineAppearance" format="reference"/>
        <attr name="bottomLineAppearance" format="reference"/>
    </declare-styleable>
    <declare-styleable name="inputTextAppearance">
        <attr name="hintColor" format="color" />
        <attr name="inputColor" format="color" />
        <attr name="textSize" format="dimension" />
        <attr name="maxInputLength" format="integer" />
    </declare-styleable>
    <declare-styleable name="titleTextAppearance">
        <attr name="titleColor" format="color" />
        <attr name="titleSize" format="dimension" />
        <attr name="minWidth" format="dimension" />
    </declare-styleable>


    <declare-styleable name="lineAppearance">
        <attr name="color" format="color" />
        <attr name="height" format="dimension" />
        <attr name="leftMargin" format="dimension" />
        <attr name="rightMargin" format="dimension" />
        <attr name="enable" format="boolean" />
    </declare-styleable>
</resources>

自定义属性都需要包裹在declare-styleable标签中,name属性标志这个属性集合的名字,其中的attr标志属性。对于自定义属性的类型,主要的有以下几种

string字符串类型 reference引用类型,一般是指向另外的一个资源属性 color颜色代码 dimension尺寸 float浮点型 boolean布尔型 integer整型 enum枚举型

当你定义完上面的文件,接下来我们需要在自定义View中解析它们,从而获得用户传递进来的属性。 属性的解析可以使用以下代码完成

val array = context.obtainStyledAttributes(attributeSet, R.styleable.InputItemLayout)
val title = array.getString(R.styleable.InputItemLayout_title)
val titleResId = array.getResourceId(R.styleable.InputItemLayout_titleTextAppearance, 0)

上面的代码中,第一句是通过obtainStyledAttributes解析上面XML文件中属性名为InputItemLayout的属性内容,并返回TypedArray,后续该命名空间中的所有属性都可以通过TypedArray.getXX()来获得XX是属性类型。

但是引用类型除外,因为引用类型中还包含了其他属性,所以需要如下代码去提取属性。

val array1 = context.obtainStyledAttributes(attributeSet, R.styleable.InputItemLayout)
val titleResId = array1.getResourceId(R.styleable.InputItemLayout_titleTextAppearance, 0)
val array = context.obtainStyledAttributes(titleResId, R.styleable.titleTextAppearance)
val titleColor = array.getColor(
    R.styleable.titleTextAppearance_titleColor,
    resources.getColor(R.color.color_565)
)

如上代码,我们先获取在InputItemLayout属性中titleTextAppearance的属性,这时候发现titleTextAppearance是一个引用类型的属性,在使用 context.obtainStyledAttributes(titleResId, R.styleable.titleTextAppearance)获取titleTextAppearance中的属性值,第一个参数titleResId是titleTextAppearance的资源ID。 最终我们获取了所有的属性,这时候就可以开始自定义你的View了。

当我们最终完成了所有的代码,怎么在布局文件中使用呢。对于普通的属性,如String Int等就和平常一样,但是对于引用类型,我们需要在style.xml文件中定义资源文件

<com.slowtd.tcommon.InputItemLayout
   android:layout_marginTop="10dp"
   android:layout_width="match_parent"
   android:layout_height="55dp"
   app:hint="请输入密码"
   app:title="密码"
   app:inputType="text"
   app:titleTextAppearance="@style/titleTextAppearance"
   app:inputTextAppearance="@style/inputTextAppearance_limitLength"
   app:topLineAppearance="@style/lineAppearance"
   app:bottomLineAppearance="@style/lineAppearance"
   />
<style name="inputTextAppearance">
   <item name="hintColor">@color/color_C1B</item>
   <item name="inputColor">@color/color_565</item>
   <item name="textSize">15sp</item>
</style>

<style name="inputTextAppearance_limitLength" parent="inputTextAppearance">
   <item name="maxInputLength">4</item>
</style>
<style name="titleTextAppearance">
   <item name="titleColor">@color/color_565</item>
   <item name="titleSize">15sp</item>
   <item name="minWidth">100dp</item>
</style>
<style name="lineAppearance">
   <item name="color">@color/black</item>
   <item name="height">2dp</item>
   <item name="leftMargin">0dp</item>
   <item name="rightMargin">0dp</item>
   <item name="enable">true</item>
</style>

下面的代码是一个简单的自定义输入框代码,供大家参考,配合上面的XML属性资源就可以使用了。

class InputItemLayout : LinearLayout {
   private lateinit var titleView: TextView
   private lateinit var editText: EditText
   private var bottomLine: Line
   private var topLine: Line
   private var topPaint = Paint(Paint.ANTI_ALIAS_FLAG)
   private var bottomPaint = Paint(Paint.ANTI_ALIAS_FLAG)

   constructor(context: Context) : this(context, null)
   constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
   constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(
       context,
       attributeSet,
       defStyle
   ) {
       dividerDrawable = ColorDrawable()
       showDividers = SHOW_DIVIDER_BEGINNING

       //去加载 去读取 自定义sytle属性
       orientation = HORIZONTAL
       val array = context.obtainStyledAttributes(attributeSet, R.styleable.InputItemLayout)

       //解析title 属性
       val title = array.getString(R.styleable.InputItemLayout_title)
       val titleResId = array.getResourceId(R.styleable.InputItemLayout_titleTextAppearance, 0)
       parseTitleStyle(title, titleResId)

       //解析右侧的输入框属性
       val hint = array.getString(R.styleable.InputItemLayout_hint)
       val inputResId = array.getResourceId(R.styleable.InputItemLayout_inputTextAppearance, 0)
       val inputType = array.getInteger(R.styleable.InputItemLayout_inputType, 0)
       parseInputStyle(hint, inputResId, inputType)
       //上下分割线属性
       val topResId = array.getResourceId(R.styleable.InputItemLayout_topLineAppearance, 0)
       val bottomResId = array.getResourceId(R.styleable.InputItemLayout_bottomLineAppearance, 0)
       topLine = parseLineStyle(topResId)
       bottomLine = parseLineStyle(bottomResId)

       if (topLine.enable) {
           topPaint.color = topLine.color
           topPaint.style = Paint.Style.FILL_AND_STROKE
           topPaint.strokeWidth = topLine.height
       }
       if (bottomLine.enable) {
           bottomPaint.color = bottomLine.color
           bottomPaint.style = Paint.Style.FILL_AND_STROKE
           bottomPaint.strokeWidth = bottomLine.height
       }
       array.recycle()
   }
   @SuppressLint("CustomViewStyleable")
   private fun parseLineStyle(resId: Int): Line {
       val line = Line()
       val array = context.obtainStyledAttributes(resId, R.styleable.lineAppearance)
       line.color =
           array.getColor(
               R.styleable.lineAppearance_color,
               ContextCompat.getColor(context, R.color.color_d1d2)
           )
       line.height = array.getDimensionPixelOffset(R.styleable.lineAppearance_height, 0).toFloat()
       line.leftMargin =
           array.getDimensionPixelOffset(R.styleable.lineAppearance_leftMargin, 0).toFloat()
       line.rightMargin =
           array.getDimensionPixelOffset(R.styleable.lineAppearance_rightMargin, 0).toFloat()
       line.enable = array.getBoolean(R.styleable.lineAppearance_enable, false)

       array.recycle()
       return line
   }
   inner class Line {
       var color = 0
       var height = 0f
       var leftMargin = 0f
       var rightMargin = 0f;
       var enable: Boolean = false
   }
   @SuppressLint("CustomViewStyleable")
   private fun parseInputStyle(hint: String?, resId: Int, inputType: Int) {

       val array = context.obtainStyledAttributes(resId, R.styleable.inputTextAppearance)

       val hintColor = array.getColor(
           R.styleable.inputTextAppearance_hintColor,
           ContextCompat.getColor(context, R.color.color_d1d2)
       )
       val inputColor = array.getColor(
           R.styleable.inputTextAppearance_inputColor,
           ContextCompat.getColor(context, R.color.color_565)
       )
       //px
       val textSize = array.getDimensionPixelSize(
           R.styleable.inputTextAppearance_textSize,
           applyUnit(TypedValue.COMPLEX_UNIT_SP, 15f)
       )
       val maxInputLength = array.getInteger(R.styleable.inputTextAppearance_maxInputLength, 0)

       editText = EditText(context)
       if (maxInputLength > 0) {
           editText.filters = arrayOf(InputFilter.LengthFilter(maxInputLength))//最多可输入的字符数
       }
       editText.setPadding(0, 0, 0, 0)
       val params = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)
       params.weight = 1f
       editText.layoutParams = params
       editText.hint = hint
       editText.setTextColor(inputColor)
       editText.setHintTextColor(hintColor)
       editText.gravity = LEFT or (CENTER)
       editText.setBackgroundColor(Color.TRANSPARENT)
       editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize.toFloat())
       /**
        * <enum name="text" value="0"></enum>
        * <enum name="password" value="1"></enum>
        * <enum name="number" value="2"></enum>
        */
       if (inputType == 0) {
           editText.inputType = InputType.TYPE_CLASS_TEXT
       } else if (inputType == 1) {
           editText.inputType =
               InputType.TYPE_TEXT_VARIATION_PASSWORD or (InputType.TYPE_CLASS_TEXT)
       } else if (inputType == 2) {
           editText.inputType = InputType.TYPE_CLASS_NUMBER
       }
       addView(editText)
       array.recycle()
   }
   @SuppressLint("CustomViewStyleable")
   private fun parseTitleStyle(title: String?, resId: Int) {
       val array = context.obtainStyledAttributes(resId, R.styleable.titleTextAppearance)
       val titleColor = array.getColor(
           R.styleable.titleTextAppearance_titleColor,
           resources.getColor(R.color.color_565)
       )
       //px
       val titleSize = array.getDimensionPixelSize(
           R.styleable.titleTextAppearance_titleSize,
           applyUnit(TypedValue.COMPLEX_UNIT_SP, 15f)
       )
       val minWidth = array.getDimensionPixelOffset(R.styleable.titleTextAppearance_minWidth, 0)

       titleView = TextView(context)
       titleView.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleSize.toFloat())  //sp---当做sp在转换一次
       titleView.setTextColor(titleColor)
       titleView.layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)
       titleView.minWidth = minWidth
       titleView.gravity = LEFT or (CENTER)
       titleView.text = title
       addView(titleView)
       array.recycle()
   }
   override fun onDraw(canvas: Canvas?) {
       super.onDraw(canvas)


       //巨坑
       if (topLine.enable) {
           canvas!!.drawLine(
               topLine.leftMargin,
               0f,
               measuredWidth - topLine.rightMargin,
               0f,
               topPaint
           )
       }

       if (bottomLine.enable) {
           canvas!!.drawLine(
               bottomLine.leftMargin,
               height - bottomLine.height,
               measuredWidth - bottomLine.rightMargin,
               height - bottomLine.height,
               bottomPaint
           )
       }
   }
   private fun applyUnit(applyUnit: Int, value: Float): Int {
       return TypedValue.applyDimension(applyUnit, value, resources.displayMetrics).toInt()
   }
   fun getTitleView(): TextView {
       return titleView
   }
   fun getEditText(): EditText {
       return editText
   }
}

到此这篇关于Android如何通过组合的方式自定义View的文章就介绍到这了,更多相关Android自定义View内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

Android如何通过组合的方式自定义View的更多相关文章

  1. html5 canvas合成海报所遇问题及解决方案总结

    这篇文章主要介绍了html5 canvas合成海报所遇问题及解决方案总结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Html5 video标签视频的最佳实践

    这篇文章主要介绍了Html5 video标签视频的最佳实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  3. HTML5在微信内置浏览器下右上角菜单的调整字体导致页面显示错乱的问题

    HTML5在微信内置浏览器下,在右上角菜单的调整字体导致页面显示错乱的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

  4. ios – containerURLForSecurityApplicationGroupIdentifier:在iPhone和Watch模拟器上给出不同的结果

    我使用默认的XCode模板创建了一个WatchKit应用程序.我向iOSTarget,WatchkitAppTarget和WatchkitAppExtensionTarget添加了应用程序组权利.(这是应用程序组名称:group.com.lombax.fiveminutes)然后,我尝试使用iOSApp和WatchKitExtension访问共享文件夹URL:延期:iOS应用:但是,测试NSURL

  5. ios – 如何在父视图上添加子视图控制器的视图

    再现.从而:

  6. Ionic – Splash Screen适用于iOS,但不适用于Android

    我有一个离子应用程序,其中使用CLI命令离子资源生成的启动画面和图标iOS版本与正在渲染的启动画面完美配合,但在Android版本中,只有在加载应用程序时才会显示白屏.我检查了config.xml文件,所有路径看起来都是正确的,生成的图像出现在相应的文件夹中.(我使用了splash.psd模板来生成它们.我错过了什么?这是config.xml文件供参考,我觉得我在这里做错了–解决方法在config.xml中添加以下键:它对我有用!

  7. ios – 实例化ViewController w / xib时的帧大小不正确

    我有一个视图控制器,看起来像:当我通过让spotViewController=SpotViewController实例化视图控制器并将其推送到导航控制器时,结果框架在viewDidLoad和viewWillAppear中都是不正确的.它给了我这是界面构建器中的大小.为什么会发生这种情况以及使用xib实例化视图控制器以确保帧正确的正确方法是什么?解决方法这将解决您的问题,UIViewController从xib加载,在viewDidLoad期间保持xib大小:

  8. ios – 无法启动iPhone模拟器

    /Library/Developer/CoreSimulator/Devices/530A44CB-5978-4926-9E91-E9DBD5BFB105/data/Containers/Bundle/Application/07612A5C-659D-4C04-ACD3-D211D2830E17/ProductName.app/ProductName然后,如果您在Xcode构建设置中选择标准体系结构并再次构建和运行,则会产生以下结果:dyld:lazysymbolbindingFailed:Symbol

  9. Xamarin iOS图像在Grid内部重叠

    heyo,所以在Xamarin我有一个使用并在其中包含一对,所有这些都包含在内.这在Xamarin.Android中看起来完全没问题,但是在Xamarin.iOS中,图像与标签重叠.我不确定它的区别是什么–为什么它在Xamarin.Android中看起来不错但在iOS中它的全部都不稳定?

  10. ios – CAGradientLayer不工作

    参见英文答案>DrawinggradientonUIViewnotworkingwithiOS91个我创建了一个新项目.我链接了QuartzCore.framework并导入了在ViewController.m中.这是代码.我尝试将视图的背景颜色设置为clearColor,在viewDidAppear中调用它,但它们都没有工作.我真的不知道自己错过

随机推荐

  1. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Android单选按钮RadioButton的使用详解

    今天小编就为大家分享一篇关于Android单选按钮RadioButton的使用详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  3. 解决android studio 打包发现generate signed apk 消失不见问题

    这篇文章主要介绍了解决android studio 打包发现generate signed apk 消失不见问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

  4. Android 实现自定义圆形listview功能的实例代码

    这篇文章主要介绍了Android 实现自定义圆形listview功能的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 详解Android studio 动态fragment的用法

    这篇文章主要介绍了Android studio 动态fragment的用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. Android用RecyclerView实现图标拖拽排序以及增删管理

    这篇文章主要介绍了Android用RecyclerView实现图标拖拽排序以及增删管理的方法,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下

  7. Android notifyDataSetChanged() 动态更新ListView案例详解

    这篇文章主要介绍了Android notifyDataSetChanged() 动态更新ListView案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  8. Android自定义View实现弹幕效果

    这篇文章主要为大家详细介绍了Android自定义View实现弹幕效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. Android自定义View实现跟随手指移动

    这篇文章主要为大家详细介绍了Android自定义View实现跟随手指移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android实现多点触摸操作

    这篇文章主要介绍了Android实现多点触摸操作,实现图片的放大、缩小和旋转等处理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部