Android自己定义View实现非常easy
继承View,重写构造函数、onDraw。(onMeasure)等函数。
假设自己定义的View须要有自己定义的属性。须要在values下建立attrs.xml。
在当中定义你的属性。
在使用到自己定义View的xml布局文件里须要增加xmlns:前缀="http://schemas.android.com/apk/res/你的应用所在的包路径".
在使用自己定义属性的时候。使用前缀:属性名,如my:textColor="#FFFFFFF"。
实例:
package demo.view.my;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.View;
/**
* 这个是自己定义的TextView.
* 至少须要重载构造方法和onDraw方法
* 对于自己定义的View假设没有自己独特的属性。能够直接在xml文件里使用就能够了
* 假设含有自己独特的属性,那么就须要在构造函数中获取属性文件attrs.xml中自己定义属性的名称
* 并依据须要设定默认值,放在在xml文件里未定义。
* 假设使用自己定义属性,那么在应用xml文件里须要加上新的schemas,
* 比方这里是xmlns:my="http://schemas.android.com/apk/res/demo.view.my"
* 当中xmlns后的“my”是自己定义的属性的前缀,res后的是我们应用所在的包
* @author Administrator
*
*/
public class MyView extends View { Paint mPaint; //画笔,包括了画几何图形、文本等的样式和颜色信息
public MyView(Context context) {
super(context); } public MyView(Context context, AttributeSet attrs){
super(context, attrs);
mPaint = new Paint();
//TypedArray是一个用来存放由context.obtainStyledAttributes获得的属性的数组
//在使用完毕后,一定要调用recycle方法
//属性的名称是styleable中的名称+“_”+属性名称
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00); //提供默认值,放置未指定
float textSize = array.getDimension(R.styleable.MyView_textSize, 36);
mPaint.setColor(textColor);
mPaint.setTextSize(textSize); array.recycle(); //一定要调用,否则这次的设定会对下次的使用造成影响
} public void onDraw(Canvas canvas){
super.onDraw(canvas);
//Canvas中含有非常多绘图的接口,利用这些接口,我们能够画出我们想要的图形
//mPaint = new Paint();
//mPaint.setColor(Color.RED);
mPaint.setStyle(Style.FILL); //设置填充
canvas.drawRect(10, 10, 100, 100, mPaint); //绘制矩形 mPaint.setColor(Color.BLUE);
canvas.drawText("我是被画出来的", 10, 120, mPaint);
}
}
对应的属性文件:
<?xml version="1.0" encoding="utf-8"? >
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color"/>
<attr name="textSize" format="dimension"/>
</declare-styleable>
</resources>
在布局文件里的使用:
<? xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:my="http://schemas.android.com/apk/res/demo.view.my"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
> <demo.view.my.MyView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
my:textColor="#FFFFFFFF"
my:textSize="22dp"
/>
</LinearLayout>
注意事项:
做Android布局是件非常享受的事。这得益于他良好的xml方式。使用xml能够高速 有效的为软件定义界面。但是有时候我们总感觉官方定义的一些基本组件不够用。自己定义组件就不可避免了。那么怎样才干做到像官方提供的那些组件一样用xml 来定义他的属性呢?如今我们就来讨论一下他的使用方法。
一、在res/values文件下定义一个attrs.xml文件。代码例如以下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToolBar">
<attr name="buttonNum" format="integer"/>
<attr name="itemBackground" format="reference|color"/>
</declare-styleable>
</resources>
二、在布局xml中例如以下使用该属性:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:toolbar="http://schemas.android.com/apk/res/cn.zzm.toolbar"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<cn.zzm.toolbar.ToolBar android:id="@+id/gridview_toolbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/control_bar"
android:gravity="center"
toolbar:buttonNum="5"
toolbar:itemBackground="@drawable/control_bar_item_bg"/>
</RelativeLayout>
三、在自己定义组件中,能够例如以下获得xml中定义的值:
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar);
buttonNum = a.getInt(R.styleable.ToolBar_buttonNum, 5);
itemBg = a.getResourceId(R.styleable.ToolBar_itemBackground, -1);a.recycle();
就这么简单的三步,就可以完毕对自己定义属性的使用。
*********************************************************************
好了。基本使用方法已经讲完了。如今来看看一些注意点和知识点吧。
首先来看看attrs.xml文件。
该文件是定义属性名和格式的地方,须要用<declare-styleable name="ToolBar"></declare-styleable>包围全部属性。当中name为该属性集的名字,主要用途是标 识该属性集。
那在什么地方会用到呢?主要是在第三步。
看到没?在获取某属性标识时,用 到"R.styleable.ToolBar_buttonNum",非常显然,他在每一个属性前面都加了"ToolBar_"。
在来看看各种属性都有些什么类型吧:string , integer , dimension , reference , color , enum.
前面几种的声明方式都是一致的,比如:<attr name="buttonNum" format="integer"/>。
仅仅有enum是不同的。使用方法举例:
<attr name="testEnum">
<enum name="fill_parent" value="-1"/>
<enum name="wrap_content" value="-2"/>
</attr>
假设该属性可同一时候传两种不同的属性,则能够用“|”切割开就可以。
让我们再来看看布局xml中须要注意的事项。
首先得声明一下:xmlns:toolbar=http://schemas.android.com/apk/res/cn.zzm.toolbar
注意。“toolbar”能够换成其它的不论什么名字。后面的url地址必须最后一部分必须用上自己定义组件的包名。
自己定义属性了。在属性名前加上“toolbar”就可以。
最后来看看java代码中的注意事项。
在自己定义组件的构造函数中,用
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar);
来获得对属性集的引用,然后就能够用“a”的各种方法来获取对应的属性值了。
这里须要注意的是。假设使用的方法和获取值的类型不正确的话,则会返回默 认值。
因此,假设一个属性是带两个及以上不用类型的属性,须要做多次推断,知道读取完成后才干推断应该赋予何值。
当然。在取完值的时候别忘了回收资源哦!
属性具体解释:
1. reference:參考某一资源ID。
(1)属性定义:
<declare-styleable name = "名称">
<attr name = "background" format = "reference" />
</declare-styleable>
(2)属性使用:
<ImageView
android:layout_width = "42dip"
android:layout_height = "42dip"
android:background = "@drawable/图片ID"
/>
2. color:颜色值。
(1)属性定义:
<declare-styleable name = "名称">
<attr name = "textColor" format = "color" />
</declare-styleable>
(2)属性使用:
<TextView
android:layout_width = "42dip"
android:layout_height = "42dip"
android:textColor = "#00FF00"
/>
3. boolean:布尔值。
(1)属性定义:
<declare-styleable name = "名称">
<attr name = "focusable" format = "boolean" />
</declare-styleable>
(2)属性使用:
<Button
android:layout_width = "42dip"
android:layout_height = "42dip"
android:focusable = "true"
/>
4. dimension:尺寸值。
(1)属性定义:
<declare-styleable name = "名称">
<attr name = "layout_width" format = "dimension" />
</declare-styleable>
(2)属性使用:
<Button
android:layout_width = "42dip"
android:layout_height = "42dip"
/>
5. float:浮点值。
(1)属性定义:
<declare-styleable name = "AlphaAnimation">
<attr name = "fromAlpha" format = "float" />
<attr name = "toAlpha" format = "float" />
</declare-styleable>
(2)属性使用:
<alpha
android:fromAlpha = "1.0"
android:toAlpha = "0.7"
/>
6. integer:整型值。 (1)属性定义:
<declare-styleable name = "AnimatedRotateDrawable">
<attr name = "visible" />
<attr name = "frameDuration" format="integer" />
<attr name = "framesCount" format="integer" />
<attr name = "pivotX" />
<attr name = "pivotY" />
<attr name = "drawable" />
</declare-styleable>
(2)属性使用:
<animated-rotate
xmlns:android = "http://schemas.android.com/apk/res/android"
android:drawable = "@drawable/图片ID"
android:pivotX = "50%"
android:pivotY = "50%"
android:framesCount = "12"
android:frameDuration = "100"
/>
7. string:字符串。
(1)属性定义:
<declare-styleable name = "MapView">
<attr name = "apiKey" format = "string" />
</declare-styleable>
(2)属性使用:
<com.google.android.maps.MapView
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:apiKey = "0jOkQ80oD1JL9C6HAja99uGXCRiS2CGjKO_bc_g"
/>
8. fraction:百分数。
(1)属性定义:
<declare-styleable name="RotateDrawable">
<attr name = "visible" />
<attr name = "fromDegrees" format = "float" />
<attr name = "toDegrees" format = "float" />
<attr name = "pivotX" format = "fraction" />
<attr name = "pivotY" format = "fraction" />
<attr name = "drawable" />
</declare-styleable>
(2)属性使用:
<rotate
xmlns:android = "http://schemas.android.com/apk/res/android"
android:interpolator = "@anim/动画ID"
android:fromDegrees = "0"
android:toDegrees = "360"
android:pivotX = "200%"
android:pivotY = "300%"
android:duration = "5000"
android:repeatMode = "restart"
android:repeatCount = "infinite"
/>
9. enum:枚举值。
(1)属性定义:
<declare-styleable name="名称">
<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
(2)属性使用:
<LinearLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
>
</LinearLayout>
10. flag:位或运算。
(1)属性定义:
<declare-styleable name="名称">
<attr name="windowSoftInputMode">
<flag name = "stateUnspecified" value = "0" />
<flag name = "stateUnchanged" value = "1" />
<flag name = "stateHidden" value = "2" />
<flag name = "stateAlwaysHidden" value = "3" />
<flag name = "stateVisible" value = "4" />
<flag name = "stateAlwaysVisible" value = "5" />
<flag name = "adjustUnspecified" value = "0x00" />
<flag name = "adjustResize" value = "0x10" />
<flag name = "adjustPan" value = "0x20" />
<flag name = "adjustNothing" value = "0x30" />
</attr>
</declare-styleable>
(2)属性使用:
<activity
android:name = ".StyleAndThemeActivity"
android:label = "@string/app_name"
android:windowSoftInputMode = "stateUnspecified | stateUnchanged | stateHidden">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
注意:
属性定义时能够指定多种类型值。
(1)属性定义:
<declare-styleable name = "名称">
<attr name = "background" format = "reference|color" />
</declare-styleable>
(2)属性使用:
<ImageView
android:layout_width = "42dip"
android:layout_height = "42dip"
android:background = "@drawable/图片ID|#00FF00"
/>
自己定义组合控件:
第一个实现一个带图片和文字的button,如图所看到的:
整个过程能够分四步走。第一步,定义一个layout,实现button内部的布局。
代码例如以下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iv"
android:src="@drawable/confirm"
android:paddingTop="5dip"
android:paddingBottom="5dip"
android:paddingLeft="40dip"
android:layout_gravity="center_vertical"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="确定"
android:textColor="#000000"
android:id="@+id/tv"
android:layout_marginLeft="8dip"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
这个xml实现一个左图右字的布局,接下来写一个类继承LinearLayout,导入刚刚的布局。而且设置须要的方法,从而使的能在代码中控制这个自己定义控件内容的显示。
代码例如以下:
package com.notice.ib; import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView; public class ImageBt extends LinearLayout { private ImageView iv;
private TextView tv; public ImageBt(Context context) {
this(context, null);
} public ImageBt(Context context, AttributeSet attrs) {
super(context, attrs);
// 导入布局
LayoutInflater.from(context).inflate(R.layout.custombt, this, true);
iv = (ImageView) findViewById(R.id.iv);
tv = (TextView) findViewById(R.id.tv); } /**
* 设置图片资源
*/
public void setImageResource(int resId) {
iv.setImageResource(resId);
} /**
* 设置显示的文字
*/
public void setTextViewText(String text) {
tv.setText(text);
} }
第三步,在须要使用这个自己定义控件的layout中增加这控件,仅仅须要在xml中增加就可以。方法例如以下:
<RelativeLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
>
<com.notice.ib.ImageBt
android:id="@+id/bt_confirm"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/btbg"
android:clickable="true"
android:focusable="true"
/>
<com.notice.ib.ImageBt
android:id="@+id/bt_cancel"
android:layout_toRightOf="@id/bt_confirm"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/btbg"
android:clickable="true"
android:focusable="true"
/>
</RelativeLayout>
注意的是,控件标签使用完整的类名就可以。为了给button一个点击效果。你须要给他一个selector背景,这里就不说了。
最后一步,即在activity中设置该控件的内容。当然,在xml中也能够设置。可是仅仅能设置一个。当我们须要两次使用这种控件。而且显示内容 不同一时候就不行了。在activity中设置也很easy。我们在ImageBt这个类中已经写好了对应的方法,简单调用就可以。代码例如以下:
public class MainActivity extends Activity { private ImageBt ib1;
private ImageBt ib2; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login); ib1 = (ImageBt) findViewById(R.id.bt_confirm);
ib2 = (ImageBt) findViewById(R.id.bt_cancel); ib1.setTextViewText("确定");
ib1.setImageResource(R.drawable.confirm);
ib2.setTextViewText("取消");
ib2.setImageResource(R.drawable.cancel); ib1.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
//在这里能够实现点击事件
}
}); }
}
这样,一个带文字和图片的组合button控件就完毕了。这样梳理一下,使用还是很easy的。
组合控件能做的事还许多。主要是在类似上例中的ImageBt类中写好要使用的方法就可以。
再来看一个组合控件。带删除button的EidtText。即在用户输入后。会出现删除button。点击就可以取消用户输入。
定义方法和上例一样。
首先写一个自己定义控件的布局:
<?xml version="1.0" encoding="utf-8"? >
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/et"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
/>
<ImageButton
android:id="@+id/ib"
android:visibility="gone"
android:src="@drawable/menu_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_alignRight="@+id/et" />
</RelativeLayout>
实现输入框右側带button效果,注意将button隐藏。然后写一个EditCancel类。实现删除用户输入功能。这里用到了TextWatch这个接口。监听输入框中的文字变化。使用也非常easy。实现他的三个方法就可以。看代码:
package com.notice.ce; import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout; public class EditCancel extends LinearLayout implements EdtInterface { ImageButton ib;
EditText et; public EditCancel(Context context) {
super(context); } public EditCancel(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.custom_editview, this, true);
init(); } private void init() {
ib = (ImageButton) findViewById(R.id.ib);
et = (EditText) findViewById(R.id.et);
et.addTextChangedListener(tw);// 为输入框绑定一个监听文字变化的监听器
// 加入button点击事件
ib.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
hideBtn();// 隐藏button
et.setText("");// 设置输入框内容为空
}
}); } // 当输入框状态改变时。会调用对应的方法
TextWatcher tw = new TextWatcher() { @Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub } @Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub } // 在文字改变后调用
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
hideBtn();// 隐藏button
} else {
showBtn();// 显示button
} } }; @Override
public void hideBtn() {
// 设置button不可见
if (ib.isShown()) ib.setVisibility(View.GONE); } @Override
public void showBtn() {
// 设置button可见
if (!ib.isShown()) ib.setVisibility(View.VISIBLE); } } interface EdtInterface { public void hideBtn(); public void showBtn(); }
在TextWatch接口的afterTextChanged方法中对文字进行推断。若长度为0。就隐藏button,否则,显示button。
另外。实现ImageButton(即那个叉)的点击事件,删除输入框中的内容,并隐藏button。
后面两步的实现就是增加到实际布局中,就不再写出来了,和上例的步骤一样的。
最后显示效果如图:
学会灵活的使用组合控件,对UI开发会有非常大帮助。
Android 自己定义控件外观
首先我们看下系统的RadioButton:
RadioButton长成什么样子是由其Background、Button等属性决定的。Android系统
使用style定义了默认的属性。在android源代码
android/frameworks/base/core/res/res/values/styles.xml中能够看到默认的定义:
<style name="Widget.CompoundButton.RadioButton">
<item name="android:background">@android:drawable/btn_radio_label_background</item>
<item name="android:button">@android:drawable/btn_radio</item>
</style>
即其背景图是btn_radio_label_background,其button的样子是btn_radio
btn_radio_label_background是什么?
其路径是android/frameworks/base/core/res/res/drawable-mdpi/btn_radio_label_background.9.png
能够看到是一个NinePatch图片,用来做背景,能够拉伸填充。
btn_radio是什么?
其路径是android/frameworks/base/core/res/res/drawable/btn_radio.xml
是个xml定义的drawable。打开看其内容:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_on" />
<item android:state_checked="false" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_off" /> <item android:state_checked="true" android:state_pressed="true"
android:drawable="@drawable/btn_radio_on_pressed" />
<item android:state_checked="false" android:state_pressed="true"
android:drawable="@drawable/btn_radio_off_pressed" /> <item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/btn_radio_on_selected" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/btn_radio_off_selected" /> <item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>
定义了不同状态下radioButton长成什么样子。
假设不知道selector是什么。就要去看下Android SDK文档中Dev Guide->Application Resources->Resource Types。
以以下一个item为例:
<item android:state_checked="true" android:state_pressed="true"
android:drawable="@drawable/btn_radio_on_pressed" />
意思即为当radiobutton被选中时。而且被按下时。其Button应该长成btn_radio_on_pressed这个样子。
文件是android/frameworks/base/core/res/res/drawable-mdpi/btn_radio_on_pressed.png
drawable的item中能够有下面属性:
android:drawable="@[package:]drawable/drawable_resource"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_active=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"]
当button的状态和某个item匹配后,就会使用此item定义的drawable作为button图片。
从上面分析我们假设要改动RadioButton的外观,那么步骤应该是:
(1)制作一个9patch的图片作为背景图
准备一副PNG图片,当中白色为透明色,是否须要透明各人依据自己须要决定。
执行SDK/tools/draw9patch
在可伸缩的范围周围加上黑色的线告知系统这些区域能够伸缩。
制作完的图片,周围多了黑色线。
(2)针对不同的状态提供button图片
enabled, on: 紫色外框、红色中心点
enabled, off:仅仅有紫色外框
enabled, on, pressed:黄色外框。红色中心点
enabled, off, pressed:黄色外框
disabled, on: 灰色外框、灰色中心点
disabled, off: 灰色外框
其余的状态此处就不再定义。
(3)使用xml描写叙述一个drawable
在res/drawable/创建custom_radio_btn.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_checked="true" android:state_pressed="true"
android:drawable="@drawable/enabled_on_pressed" /> <item android:state_enabled="true" android:state_checked="false" android:state_pressed="true"
android:drawable="@drawable/enabled_off_pressed" /> <item android:state_enabled="true" android:state_checked="true"
android:drawable="@drawable/enabled_on" /> <item android:state_enabled="true" android:state_checked="false"
android:drawable="@drawable/enabled_off" /> <item android:state_enabled="false" android:state_checked="true"
android:drawable="@drawable/disabled_on" /> <item android:state_enabled="false" android:state_checked="false"
android:drawable="@drawable/disabled_off" />
</selector>
Item顺序是有讲究的,条件限定越仔细,则应该放到前面。
比方这儿假设把1,2行和3,4行的item交换,那么pressed的就永远无法触发了。由于有item已经满足条件返回了。能够理解为代码中的if语句。
(4)创建一个自己定义的style。并应用到RaidioButton的style属性上
<style name="CustomRadioBtn">
<item name="android:background">@drawable/radio_btn_bg</item>
<item name="android:button">@drawable/custom_radio_btn</item>
</style>
执行ap就可以看到此RadioButton的外观已经改变。此demo能够看到文字被button遮盖了一部分,
这儿是因第一步制作9patch图片时没有留出button图片空间来。稍作改动就可以。