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

Android开发_自定义视图和属性

2015-03-25 14:50 295 查看
1、自定义视图:可以通过继承View类,并重写其onDraw()方法来实现。

2、自定义属性:可以在values文件夹下新增一个名为attrs.xml的文件,增加自定义的属性。如果要在布局中使用自定义的属性,则要为其增加命名空间:xmlns:msx="http://schemas.android.com/apk/res/com.example.mydemo;其中的msx为任意命名,而最后的com.example.mydemo为AndroidManifest.xml文件中系统的包名。如果要在类中使用自定义属性,则可以通过context.obtainStyledAttributes(attrs,R.styleable.MyView)方法来返回自定义属性的集合类TypedArray,通过该类就可以修改自定义属性的值。下面是例子:

// 自定义视图类
public class MyView extends View {

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

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs,
R.styleable.MyView);
int color = ta.getColor(R.styleable.MyView_my_color, 0xff00ff00);
setBackgroundColor(color);

ta.recycle();
}
}
attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="my_color" format="color" />
</declare-styleable>
</resources>
布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:msx="http://schemas.android.com/apk/res/com.example.mytext"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<com.example.mytext.MyView
android:layout_width="100dp"
android:layout_height="100dp"
msx:my_color="#ff00ffff" />
</RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android