Android使用Kotlin自定義View的方法教程

前言

創(chuàng)新互聯(lián)建站為企業(yè)級客戶提高一站式互聯(lián)網(wǎng)+設(shè)計(jì)服務(wù),主要包括成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、重慶App定制開發(fā)、微信平臺小程序開發(fā)、宣傳片制作、LOGO設(shè)計(jì)等,幫助客戶快速提升營銷能力和企業(yè)形象,創(chuàng)新互聯(lián)各部門都有經(jīng)驗(yàn)豐富的經(jīng)驗(yàn),可以確保每一個作品的質(zhì)量和創(chuàng)作周期,同時每年都有很多新員工加入,為我們帶來大量新的創(chuàng)意。 

隨著google宣布kotlin作為官方開發(fā)語言,在Android中使用kotlin的趨勢也越來越明顯,最近被kotlin的文章轟炸了,所以決定上手試一下,試過之后,感覺靠它靈簡直有魔性。特別是一句話寫出一個復(fù)雜的循環(huán)的時候,簡直被驚呆。而且使用AS,Java代碼可以直接轉(zhuǎn)成Kotlin。

效果圖如下:

Android 使用Kotlin自定義View的方法教程

首先是這次自定義View的效果圖,是一張餅圖。如果是用java寫的話也就幾十行,覺得換成Kotlin的話可能會更少。

示例代碼

主要的功能是可以任設(shè)定數(shù)據(jù)的個數(shù),我這里是4個數(shù)據(jù),可以任意設(shè)定每個數(shù)據(jù)的顏色。

#####首先上Kotlin代碼#####

package top.greendami.mykotlinapp
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
/**
 * Created by GreendaMi on 2017/4/10.
 */
class PPCircle : View {
 var mDatas = ArrayList<Float>()
 var mColors = ArrayList<Int>(4)
 var mPaint: Paint = Paint()
 constructor(mContext: Context) : super(mContext) {
 val context = mContext
 }
 constructor(mContext: Context, mAttributeSet: AttributeSet) : super(mContext, mAttributeSet) {
 initPaint()
 val context = mContext
 }
 fun initPaint() {
 mPaint.isAntiAlias = true
 mPaint.style = Paint.Style.FILL_AND_STROKE
 mPaint.color = 0xff44b391.toInt()
 }
 //長寬一致
 override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
 super.onMeasure(widthMeasureSpec, heightMeasureSpec)
 val widthSpecSize = View.MeasureSpec.getSize(widthMeasureSpec)
 val heightSpecSize = View.MeasureSpec.getSize(heightMeasureSpec)
 val mLayoutSize = Math.min(widthSpecSize, heightSpecSize)
 setMeasuredDimension(mLayoutSize, mLayoutSize)
 }
 /**
 * 設(shè)置數(shù)據(jù)
 */
 fun setData(data: ArrayList<Float>, colors: ArrayList<Int>) {
 mDatas = data
 mColors = colors
 invalidate()
 }
 override fun onDraw(canvas: Canvas?) {
 super.onDraw(canvas)
 if (mDatas.size == 0) {
  return
 }
 //切掉圓心
 var mPath = Path()
 mPath.addCircle(width / 2f, height / 2f, width / 2f * 0.4f,Path.Direction.CW)
 mPath.close()
 canvas?.clipPath(mPath, Region.Op.XOR)
 var total = 0f
 //此處亮點(diǎn)
 mDatas.forEach { total += it }
 var rf = RectF(0f, 0f, width.toFloat(), height.toFloat())
 var startAngle = -90f//起點(diǎn)
 var i = 0
 mDatas.forEach {
  mPaint.color = mColors[i]
  var sweepAngle = it * 360 / total
  canvas?.drawArc(rf, startAngle, sweepAngle, true, mPaint)
  startAngle += sweepAngle
  i++
 }
 }
}

設(shè)置數(shù)據(jù)

package top.greendami.mykotlinapp
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main2.*
class Main2Activity : AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main2)
  var mDatas = ArrayList<Float>()
  mDatas.add(1f)
  mDatas.add(2f)
  mDatas.add(4f)
  mDatas.add(2f)
  var mColors = ArrayList<Int>()
  mColors.add(0xff83ccd2.toInt())
  mColors.add(0xffc0e1ce.toInt())
  mColors.add(0xfffac55e.toInt())
  mColors.add(0xffef805f.toInt())
  ppCircle.setData(mDatas,mColors)
 }
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent" tools:context="top.greendami.mykotlinapp.Main2Activity">
 <top.greendami.mykotlinapp.PPCircle
  android:id="@+id/ppCircle"
  android:layout_width="300dp"
  android:layout_height="300dp"  app:layout_constraintBottom_toBottomOf="parent"
  android:layout_marginBottom="8dp"
  android:layout_marginRight="8dp"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent"
  android:layout_marginTop="8dp"
  android:layout_marginLeft="8dp"
  app:layout_constraintLeft_toLeftOf="parent" />
</android.support.constraint.ConstraintLayout>

#####相同功能Java代碼#####

package com.allrun.arsmartelevatorformanager.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by GreendaMi on 2017/4/11.
 */
public class PPCircle extends View {
 Context mContext;
 List<Float> mData = new ArrayList<Float>();//數(shù)據(jù)
 List<Integer> mColors = new ArrayList<Integer>();//數(shù)據(jù)對應(yīng)的顏色
 Paint mPaint = new Paint();
 public PPCircle(Context context) {
  super(context);
 }
 public PPCircle(Context context, @Nullable AttributeSet attrs) {
  super(context, attrs);
  mContext = context;
  initPaint();
 }
 private void initPaint() {
  mPaint.setAntiAlias(true);
  mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
 }
 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  int widthSpecSize = View.MeasureSpec.getSize(widthMeasureSpec);
  int heightSpecSize = View.MeasureSpec.getSize(heightMeasureSpec);
  int mLayoutSize = Math.min(widthSpecSize, heightSpecSize);
  setMeasuredDimension(mLayoutSize, mLayoutSize);
 }
 public void setData(List<Float> mData, List<Integer> mColors) {
  this.mData = mData;
  this.mColors = mColors;
 }
 @Override
 protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  if (mData.size() == 0) {
   return;
  }
  //切掉圓心
  Path mPath =new Path();
  mPath.addCircle(getWidth()/2,getWidth()/2,getWidth()/2* 0.4f ,Path.Direction.CW);
  canvas.clipPath(mPath, Region.Op.XOR);

  float total = 0;
  for(float temp : mData){
   total = total + temp;
  }
  RectF rf = new RectF(0f, 0f, getWidth(), getHeight());
  float startAngle = -90f;//起點(diǎn)
  int i = 0;
  for(float temp : mData){
   mPaint.setColor(mColors.get(i));
   float sweepAngle = temp * 360 / total;
   canvas.drawArc(rf, startAngle, sweepAngle, true, mPaint);
   startAngle += sweepAngle;
   i++;
  }
 }
}

說說Kotlin和Java感覺差異比較大的地方。首先是變量的生命,Kotlin聲明時必須賦值或者初始化,java則不用,開始有點(diǎn)不習(xí)慣。Kotlin不需要分號結(jié)尾,Kotlin的循環(huán)用起來簡直爽YY。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對創(chuàng)新互聯(lián)的支持。

網(wǎng)站標(biāo)題:Android使用Kotlin自定義View的方法教程
本文網(wǎng)址:http://muchs.cn/article26/pgoicg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)網(wǎng)站設(shè)計(jì)公司、虛擬主機(jī)、搜索引擎優(yōu)化、電子商務(wù)用戶體驗(yàn)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營