Android——自定义视图(一)转
2016-04-23 01:20
531 查看
首先,建立一个Android工程,命名MyView。
然后,自定义一个类myView,继承View类。代码如下
最后将我们自定义的View加入到main.xml布局文件中验证。
最后,一定要记得在LinearLayout标签中加入(如上面代码第三行):
xmlns:viewDemo="http://schemas.android.com/apk/res/com.android.randy.viewDemo"
不然找不到你自己定义的View。
贴图:
然后,自定义一个类myView,继承View类。代码如下
package com.android.randy.viewDemo; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Style; import android.util.AttributeSet; import android.view.View; public class myView extends View{ Paint mPaint; Context context; public static final String mString = "My first View."; public myView(Context context) { super(context); // TODO Auto-generated constructor stub //接收构造参数 this.context=context; //创建Paint对象 mPaint = new Paint(); } public myView(Context context,AttributeSet attrs){ super(context,attrs); //接收构造参数 this.context=context; //创建Paint对象 mPaint = new Paint(); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); //设置画笔颜色 mPaint.setColor(Color.GREEN); //设置mPaint属性为实心填充 mPaint.setStyle(Style.FILL); //绘制一个矩形,第一个参数是矩形的范围Rect(左,上,右,下),第二个参数为画刷 canvas.drawRect(new Rect(10, 10, 100, 100), mPaint); //设置画刷颜色 mPaint.setColor(Color.BLUE); //绘制文字,第一个参数为String类型字符串, //第二个和第三个参数为文字显示位置的左上坐标, //第四个参数为画刷 canvas.drawText(mString, 10, 120, mPaint); } }
最后将我们自定义的View加入到main.xml布局文件中验证。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:viewDemo="http://schemas.android.com/apk/res/com.android.randy.viewDemo" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <com.android.randy.viewDemo.myView android:id="@+id/myView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
最后,一定要记得在LinearLayout标签中加入(如上面代码第三行):
xmlns:viewDemo="http://schemas.android.com/apk/res/com.android.randy.viewDemo"
不然找不到你自己定义的View。
贴图:
相关文章推荐
- 新一代Android渠道打包工具:1000个渠道包只需要5秒
- 关于Android Animation的setFillBefore、setFillAfter和setFillEnable
- Android:使用adb命令行导出[数据库db3]文件
- 布局点击变色的设置
- Android——用PagerAdapter实现View滑动效果
- 触摸事件与手势监听--Android GestureDetector详解
- ListView取消分割线
- android 动态地改变某控件的大小
- Android——关于PagerAdapter的使用方法的总结(转)
- android studio 添加第三方jar
- 跟着官方学习Android — Services
- Android sdk content loader 0%的解决方案
- 第一章 JAVA入门_Learn Java for Android Development(第三版)
- android toast使用总结
- 后续_Learn Java for Android Development (第三版)
- 聊聊Android的缓存(一)
- 几个Android开发中遇到的问题
- android:向res/drawable里面添加图片+制作.9.png
- ExpandableListView的使用
- Android JNI总结