您的位置:首页 > 移动开发 > Android开发

android:自定义视图属性

2016-03-27 20:16 435 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息