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,通过该类就可以修改自定义属性的值。下面是例子:
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开发UI之自定义视图属性
- 使用Kotlin开发Android应用(IV):自定义视图和Android扩展
- android-在开发中使用自定义属性名
- Android开发技巧一--weight属性实现视图的居中(半)显示
- Android开发技巧——自定义控件之自定义属性
- Android开发技巧——自定义控件之自定义属性
- Android开发之自定义View(视图)
- Android开发之自定义View(视图)
- android自定义视图属性(atts.xml,TypedArray)学习
- (转)android自定义视图属性(atts.xml,TypedArray)学习
- Android开发之自定义属性(Define Custom Attributes)
- android自定义视图属性(atts.xml,TypedArray)学习
- android开发之自定义属性、View和使用
- android开发之自定义TextView设置字间距以及通过TextView控件属性设置行间距
- Android开发自定义View之滑动按钮与自定义属性
- Android如何自定义视图属性总结
- Android开发技巧一--weight属性实现视图的居中(半)显示
- android开发中的自定义属性用法详解
- android 自定义视图控件开发
- android自定义视图属性(atts.xml,TypedArray)学习