2015年10月14日 星期三

制作自定義的View4-使用XML修改 View




package pom.poly.com.trymakeviewbymyself.myView.v4;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;

import pom.poly.com.trymakeviewbymyself.R;
import pom.poly.com.trymakeviewbymyself.myView.v3.BasicView;

/**
 * Created by User on 14/10/2015.
 */
public class NumView extends BasicView {
    private Paint paint = new Paint();
    private String showText = "I love you";
    private int linenum=4;

    public NumView(Context context) {
        super(context);
    }

    public NumView(Context context, AttributeSet attrs) {
        super(context, attrs);
       
    }

    @Override
    protected void drawsub(Canvas canvas) {
        int textSize=100;
        for (int i = 0; i < linenum; i++) {
            textSize = textSize + i*10;
            paint.setTextSize(textSize);
            canvas.drawText(showText, 0, textSize + textSize*i, paint);
        }


    }

    @Override
    protected void logic() {

    }
}

How to no need change the code, use XML to change the number of line that show?
1.create a attrs.xml

in the xmal file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="NumView">
        <attr name="linenum" format="integer"></attr>
    </declare-styleable>
</resources>

remark:<attr name="linenum" format="integer"></attr>  定義了 linenum e個 attribute 的鄰形是 int

2. use the XML
in the activity_mian.xml
add

xmlns:nv="http://schemas.android.com/apk/res-auto"

than you can use the linenum

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:nv="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <pom.poly.com.trymakeviewbymyself.myView.v4.NumView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:id="@+id/view"
        android:layout_weight="1"
        nv:linenum="6"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/bt1" />
</LinearLayout>

3.change the program that make the program can read the value type in the XML

public NumView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.NumView);
        linenum=ta.getInt(R.styleable.NumView_linenum,0);
        ta.recycle();//release the TypedArray
    }

remark:NumView define in the attrs.xml ,
must need release the TypedArray