自定义控件Android/Java学习日记自定义view

【学习笔记】自定义控件的几种写法

2016-09-23  本文已影响421人  MarcoHorse

Android开发中给我们提供了丰富的控件支持,可是产品是不断地发展更新的,产品经理的想法有时候也是比较BUG的。当软件对UI设计的要求比较高的时候,经常会遇到安卓自带的控件无法满足自己需求的情况,这种时候,我们只能去自己去实现适合项目的控件。同时,安卓也允许你去继承已经存在的控件或者实现你自己的控件以便优化界面和创造更加丰富的用户体验。

在Android的UI界面都是由View和ViewGroup,及其派生类组合而成的!基于AndroidUI的设计原理,按道理,我们是完全可以按照自己的意愿开发出项目中所需要的UI界面的!View是所有UI界面的基类,包括ViewGroup也是继承自View,如果说一个View是一个控件,那么ViewGroup就是容纳这些控件的一个容器。

androidUI

根据图,作为容器的ViewGroup可以包含作为叶子节点的View,也可以包含作为更低层次的子ViewGroup,而子ViewGroup又可以包含下一层 的叶子节点的View和ViewGroup。事实上,这种灵活的View层次结构可以形成非常复杂的UI布局,开发者可据此设计、开发非常精致的UI界面。

下面就让我来给大家介绍一下,如何来书写这三种自定义控件!请随意吐槽

  1. 自定义属性attrs.xml的使用
  2. 基于原生控件的扩展(例子:实现与系统字体不同的TextView)
  3. 基于组合控件的扩展(例子:构建可以图文混排的LinearLayout)
  4. 自定义View(例子:波浪加载动画)

自定义属性attrs.xml的使用
attrs.xml是自定义属性的xml文件,主要作用是通过xml布局里面设置的参数然后可以传送到程序中,我们可以理解为,attrs.xml是xml布局和java代码中参数传递的桥梁!

  1. 在values文件夹中新建一个attrs.xml文件
    <pre>
    <?xml version="1.0" encoding="utf-8"?>
    <resources>

    <declare-styleable name="MineTextView">
    <attr name="color" format="color"/>
    <attr name="size" format=""/>
    </declare-styleable>
    </resources>
    </pre>

  2. 新建一个类继承自TextView并重载它的构造方法,再声明两个变量来存储自定义控件的属性,通过TypedArray获取xml布局中的属性值
    <pre>
    public class MineTextView extends TextView {
    private Context context;
    private float size;
    private int color;

    public MineTextView(Context context) {
    super(context);
    initAttrs(context,null);
    }

    public MineTextView(Context context, AttributeSet attrs) {
    super(context, attrs,0);
    initAttrs(context,attrs);
    }

    public MineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initAttrs(context,attrs);
    }

    /**

    • 初始化Attrs参数
      */
      private void initAttrs(Context context, AttributeSet attrs) {
      this.context = context;
      if (attrs == null) return;
      TypedArray typed = context.obtainStyledAttributes(attrs, R.styleable.MineTextView);
      color = typed.getColor(R.styleable.MineTextView_color, 0X00FF00);
      size = typed.getFloat(R.styleable.MineTextView_size, 32f);
      typed.recycle();//使用完记得调用recycle
      initView();
      }

    /**

    • 初始化页面
      */
      public void initView(){
      setTextColor(color);
      setTextSize(size);
      }
      }
      </pre>
  3. 在xml布局里面设置自定义控件属性
    在根布局容器内添加xmlns:app = "http://schemas.android.com/apk/res-auto"
    其中app是你自定义的命名空间,res-auto是由程序自动找资源,添加自定义控件进去Layout里面,再写多一个正常的TextView用来做对比
    <pre>
    <com.marco.minecomponents.MineTextView
    android:text="Hello World!"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:color="@color/colorPrimary"
    app:size="45"/>
    <TextView
    android:text="我是正常的TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
    </pre>
    效果如下:

效果图
  1. 基于原生控件的扩展(例子:实现与系统字体不同的TextView)
    Android系统默认支持三种字体,分别为:“****sans”, “serif”, “monospace",除此之外还可以使用其他字体文件(*.ttf)
    首先在上一个Textview的里面新建一个更改字体的方法并放进initView里面,效果如下
    try {
    Typeface face = Typeface.createFromAsset(context.getAssets(),"/FZLTCXHJW.TTF");
    setTypeface(face);
    }catch (Exception e){
    e.printStackTrace();
    Log.i("ddd","error--->"+e.getMessage());
    }
    我把字体文件放在assets文件夹下面,之后在xml布局里面添加几个系统支持的字体样式
    <TextView
    android:text="normal"
    android:typeface="normal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
    <TextView
    android:text="sans"
    android:typeface="sans"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
    <TextView
    android:text="serif"
    android:typeface="serif"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
    <TextView
    android:text="monospace"
    android:typeface="monospace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
效果图
  1. 基于组合控件的扩展(例子:构建图文混排的LinearLayout)
    网上很多都是使用TextView.fromHtml里面的imageGetter来实现图文混排,这里只是为大家简单介绍如何写自定义控件,有兴趣的可以查一下相关资料!这里会给大家演示一下如何来做一个单行文本单行图片的LinearLayoutDemo
    2.1 我们新建一个Data类用来存储数据类型和View
    private int type;//内容的类型: 1 图片 2 文本
    private View view;
    public Data(int type, View view) {
    this.type = type;
    this.view = view;
    }
    2.2 创建MineLinearLayout类继承自LinearLayout,重写三个构造方法和声明一个存储Data的数组作为数据源
    我们先写一个LinearLayout布局,因为考虑到我们的LinearLayout有可能高度越界,所以在xml外面要封装多一个ScrollView
    <pre>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
    android:id="@+id/lin"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    </LinearLayout>
    </ScrollView>
    </pre>
    2.3 之后在MineLinearLayout里面将xml的布局作为root视图,并获取其中的LinearLayout对象, 顺便说下下面代码的三个参数代表什么意思吧!
    LayoutInflater.from(context).inflate(R.layout.layout_mine, this, true);
    第一个R.layout.layout_mine, 跳过不说
    第二个this,代表返回的View的父布局,一般都是用null,在这里用this是因为我本来就继承了一个LinearLayout
    第三个是一个boolean类型,是否将返回的View作为root视图
    之后再在MineLinearLayout里面完善添加数据,更新数据,删除数据的操作
    <pre>// 初始化页面
    public void initView(Context context) {
    setOrientation(VERTICAL);//竖向分布
    LayoutInflater.from(context).inflate(R.layout.layout_mine, this, true);
    lin = (LinearLayout)findViewById(R.id.lin);
    }
    // 更新页面public void updateView() {
    for (Data data : datas) {
    lin.addView(data.getView());
    }
    }
    // 移除View
    public void removeView(int position) {
    if (position < datas.size() && position > 0) {
    lin.removeView(datas.get(position).getView());
    datas.remove(position); }
    }
    // 重设页面
    public void resetData() {
    lin.removeAllViews();
    datas.clear();
    }
    // 设置页面数据
    public void setData(ArrayList<Data> datas) {
    resetData();
    this.datas.addAll(datas);
    updateView();
    }
    // 添加页面数据
    public void addData(Data data) {
    datas.add(data);
    lin.addView(data.getView());
    }</pre>
    2.4 在MainActivity的布局里面添加自定义控件,并添加测试数据
    <pre><com.marco.minecomponents.MineLinearLayout
    android:id="@+id/mine"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"/></pre>
    <pre>public void initData(){
    ArrayList<Data> datas = new ArrayList<>();
    datas.add(new Data(0,getTextView()));
    datas.add(new Data(1,getImageView()));
    datas.add(new Data(0,getTextView()));
    datas.add(new Data(1,getImageView()));
    datas.add(new Data(0,getTextView()));
    datas.add(new Data(1,getImageView()));
    lin.setData(datas);
    }

    public View getTextView() {
    TextView tv = new TextView(this);
    tv.setText("text");
    tv.setTextSize(32);
    tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    tv.setPadding(8, 8, 8, 8);
    return tv;
    }

    public View getImageView() {
    ImageView img = new ImageView(this);
    img.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    img.setBackgroundResource(android.R.color.transparent);
    img.setImageResource(R.drawable.demo);
    return img;
    }
    </pre>

效果图
  1. 自定义View(例子:波浪动画)
    制作一个自定义的波浪动画,首先是需要先画一条曲线,我们需要使用到Android绘图Api,其中比较重要的是Paint,Path,和重写onDraw方法。而绘制波浪主要是用Path提供的quadTo方法来绘制贝塞尔曲线,其中quadTo的四个参数,分别为起始点的xy坐标和终点的xy坐标!在设置的时候,要把顶点和终点计算出来。
    3.1 声明要用的变量,通过onSizeChange方法获取视图宽高,设置画笔,在onDraw里面设置路径,根据路径来绘制曲线
    <pre>
    // 初始化画笔
    private void initPaint() {
    paint = new Paint();
    paint.setStrokeWidth(14);//设置画笔宽度
    paint.setColor(Color.argb(70, 255, 255, 255));
    paint.setAntiAlias(true);//抗锯齿
    paint.setStyle(Paint.Style.STROKE);//实线
    path = new Path();
    }

    @Override
    protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

     //画路径
     path.moveTo(0, mHeight / 2);
     path.quadTo(mWidth / 8, mHeight / 2 - waveHeight, mWidth / 4, mHeight / 2);
     path.quadTo(mWidth * 3 / 8, mHeight / 2 + waveHeight, mWidth / 2, mHeight / 2);
     path.quadTo(mWidth * 5 / 8, mHeight / 2 - waveHeight, mWidth * 3 / 4, mHeight / 2);
     path.quadTo(mWidth * 7 / 8, mHeight / 2 + waveHeight, mWidth, mHeight / 2);
     canvas.drawPath(path, paint);
    

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    //获取屏幕高度和宽度
    this.mHeight = h;
    this.mWidth = w;
    }
    </pre>

计算曲线位置 波浪效果

3.2 绘制闭合曲线
<pre>
paint.setStyle(Paint.Style.FILL);
path.lineTo(mWidth,mHeight);
path.lineTo(0,mHeight);
path.close();</pre>

3.3 下一步我们要做的就是让路径运动起来,波浪其实就是曲线向前运动而已!那么我们考虑如果有两倍长的曲线,当向前运动的距离和宽度一致的时候,是不是就可以模拟一个波浪的动画了!
下面我们来看一张图

草图

看右上角,两端波浪组成的,所以起始位置就在(0-mWidth+movePath,mHeight/2)
而第一段波浪因为还在屏幕外,所以需要涉及到横坐标的都要家还是那个movePath-mWidth,第二段加上movePath就可以了
那么,代码经过修改后就变成这样:::
<pre> //画路径
path.moveTo(movePath - mWidth, mHeight / 2);
path.quadTo(mWidth / 8 + movePath - mWidth, mHeight / 2 - waveHeight, mWidth / 4 + movePath - mWidth, mHeight / 2);
path.quadTo(mWidth * 3 / 8 + movePath - mWidth, mHeight / 2 + waveHeight, mWidth / 2 + movePath - mWidth, mHeight / 2);
path.quadTo(mWidth * 5 / 8 + movePath - mWidth, mHeight / 2 - waveHeight, mWidth * 3 / 4 + movePath - mWidth, mHeight / 2);
path.quadTo(mWidth * 7 / 8 + movePath - mWidth, mHeight / 2 + waveHeight, mWidth + movePath - mWidth, mHeight / 2);
//第二段
path.quadTo(mWidth / 8 + movePath, mHeight / 2 - waveHeight, mWidth / 4 + movePath, mHeight / 2);
path.quadTo(mWidth * 3 / 8 + movePath, mHeight / 2 + waveHeight, mWidth / 2 + movePath, mHeight / 2);
path.quadTo(mWidth * 5 / 8 + movePath, mHeight / 2 - waveHeight, mWidth * 3 / 4 + movePath, mHeight / 2);
path.quadTo(mWidth * 7 / 8 + movePath, mHeight / 2 + waveHeight, mWidth + movePath, mHeight / 2);
//闭合曲线
path.lineTo(mWidth + movePath, mHeight);
path.lineTo(movePath - mWidth, mHeight);
path.close();
//绘制曲线
canvas.drawPath(path, paint);</pre>
3.4 最后调用invalidate();重绘就可以了,至于动图我就不传了,不知道怎么传!!!囧

Paste_Image.png

最终结语:其实自定义控件博大精深,远远不止这么简单!这里只是说了一下我了解到的一下简单的技巧!自定义View里面的比较重要的方法例如,onMeasure,onLayout,矩阵变换,我都没说(我也没懂)!大家将就着看吧,如果哪里有写错或者不明白的,欢迎各种丢香蕉丢西瓜皮!

Demo地址:https://github.com/Mark911105/MineComponents.git

上一篇下一篇

猜你喜欢

热点阅读