android:自定义视图属性

android中 当默认的控件无法满足是,可通过新建一个类使其继承View,来达到自定义控件的效果

代码如下

MainActivity:

package com.example.kanzaki.learnmyview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

自定义控件MyView


package com.example.kanzaki.learnmyview;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Kanzaki on 2016/3/27.
 */
//自定义控件,使其继承自View
public class MyView extends View {
    //两个构造方法
    public MyView(Context context) {
        super(context);
    }

    //带有属性设置的构造方法
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //调用context.obtainStyledAttributes方法加载自定义的属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        //通过typedArray对象获取color
        int color = typedArray.getColor(R.styleable.MyView_my_color, 0xffff0000);
        //为背景设置颜色
        setBackgroundColor(color);

        //每次使用TypedArray后需要调用recycle()方法,当recycle被调用后,
        // 说明该对象现在可以被重复利用,不需要每次使用都重新分配内存了
        //官方解释:回收TypedArray,以便后面重用。在调用这个函数后,你就不能再使用这个TypedArray。
        typedArray.recycle();

    }
}

自定义属性myColor.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    //declare-styleable是给自定义控件添加自定义属性用的
    <declare-styleable name="MyView">
        //format属性用于限制my_color的格式,这里设置为颜色
        <attr name="my_color" format="color">

        </attr>
    </declare-styleable>


</resources>

主布局activity-main.xml


<pre name="code" class="java"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:kanzaki="http://schemas.android.com/apk/res/com.example.kanzaki.learnmyview"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.kanzaki.learnmyview.MainActivity">
    //通过完整包名来访问自定义的控件
    //可以通过在根标签中添加xmlns:kanzaki="http://schemas.android.com/apk/res/com.example.kanzaki.learnmyview"
    //对自定义属性修改
    <com.example.kanzaki.learnmyview.MyView
        android:layout_width="100dp"
        android:layout_height="100dp"
        kanzaki:my_color="@color/colorAccent"
        />
</LinearLayout>


 


自定义属性的format有很多种:

reference

string

color

boolean

dimension

integer

float

flag

fraction

enum


具体使用可参照:http://blog.csdn.net/pgalxx/article/details/6766677


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值