android自定义view控件
‘壹’ android自定义控件怎么用
一、控件自定义属性介绍
以下示例中代码均在values/attrs.xml 中定义,属性均可随意命名。
1. reference:参考某一资源ID。
示例:
<declare-styleable name = "名称">
<attr name = "background" format = "reference" />
<attr name = "src" format = "reference" />
</declare-styleable>
2. color:颜色值。
示例:
<declare-styleable name = "名称">
<attr name = "textColor" format = "color" />
</declare-styleable>
3. boolean:布尔值。
示例:
<declare-styleable name = "名称">
<attr name = "focusable" format = "boolean" />
</declare-styleable>
4. dimension:尺寸值。
示例:
<declare-styleable name = "名称">
<attr name = "layout_width" format = "dimension" />
</declare-styleable>
5. float:浮点值。
示例:
<declare-styleable name = "名称">
<attr name = "fromAlpha" format = "float" />
<attr name = "toAlpha" format = "float" />
</declare-styleable>
6. integer:整型值。
示例:
<declare-styleable name = "名称">
<attr name = "frameDuration" format="integer" />
<attr name = "framesCount" format="integer" />
</declare-styleable>
7. string:字符串。
示例:
<declare-styleable name = "名称">
<attr name = "text" format = "string" />
</declare-styleable>
8. fraction:百分数。
示例:
<declare-styleable name="名称">
<attr name = "pivotX" format = "fraction" />
<attr name = "pivotY" format = "fraction" />
</declare-styleable>
9. enum:枚举值。
示例:
<declare-styleable name="名称">
<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
10. flag:位或运算。
示例:
<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" />
</attr>
</declare-styleable>
11.多类型。
示例:
<declare-styleable name = "名称">
<attr name = "background" format = "reference|color" />
</declare-styleable>
二、属性的使用以及自定义控件的实现
1、构思控件的组成元素,思考所需自定义的属性。
比如:我要做一个 <带阴影的按钮,按钮正下方有文字说明>(类似9宫格按钮)
新建values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="custom_view">
<attr name="custom_id" format="integer" />
<attr name="src" format="reference" />
<attr name="background" format="reference" />
<attr name="text" format="string" />
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
以上,所定义为custom_view,custom_id为按钮id,src为按钮,background为阴影背景,text为按钮说明,textColor为字体颜色,textSize为字体大小。
2、怎么自定义控件呢,怎么使用这些属性呢?话不多说请看代码,CustomView :
package com.nanlus.custom;
import com.nanlus.custom.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomView extends FrameLayout implements OnClickListener {
private CustomListener customListener = null;
private Drawable mSrc = null, mBackground = null;
private String mText = "";
private int mTextColor = 0;
private float mTextSize = 20;
private int mCustomId = 0;
private ImageView mBackgroundView = null;
private ImageButton mButtonView = null;
private TextView mTextView = null;
private LayoutParams mParams = null;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.custom_view);
mSrc = a.getDrawable(R.styleable.custom_view_src);
mBackground = a.getDrawable(R.styleable.custom_view_background);
mText = a.getString(R.styleable.custom_view_text);
mTextColor = a.getColor(R.styleable.custom_view_textColor,
Color.WHITE);
mTextSize = a.getDimension(R.styleable.custom_view_textSize, 20);
mCustomId = a.getInt(R.styleable.custom_view_custom_id, 0);
mTextView = new TextView(context);
mTextView.setTextSize(mTextSize);
mTextView.setTextColor(mTextColor);
mTextView.setText(mText);
mTextView.setGravity(Gravity.CENTER);
mTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mButtonView = new ImageButton(context);
mButtonView.setImageDrawable(mSrc);
mButtonView.setBackgroundDrawable(null);
mButtonView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mButtonView.setOnClickListener(this);
mBackgroundView = new ImageView(context);
mBackgroundView.setImageDrawable(mBackground);
mBackgroundView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mBackgroundView);
addView(mButtonView);
addView(mTextView);
this.setOnClickListener(this);
a.recycle();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mParams = (LayoutParams) mButtonView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
mButtonView.setLayoutParams(mParams);
}
mParams = (LayoutParams) mBackgroundView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
mBackgroundView.setLayoutParams(mParams);
}
mParams = (LayoutParams) mTextView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
mTextView.setLayoutParams(mParams);
}
}
public void setCustomListener(CustomListener l) {
customListener = l;
}
@Override
public void onClick(View v) {
if (customListener != null) {
customListener.onCuscomClick(v, mCustomId);
}
}
public interface CustomListener {
void onCuscomClick(View v, int custom_id);
}
}
代码很简单,就不多说,下面来看看我们的CustomView是怎么用的,请看:
3、自定义控件的使用
话不多说,请看代码,main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:nanlus="http://schemas.android.com/apk/res/com.nanlus.custom"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="horizontal" >
<com.nanlus.custom.CustomView
android:id="@+id/custom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
nanlus:background="@drawable/background"
nanlus:custom_id="1"
nanlus:src="@drawable/style_button"
nanlus:text="按钮1" >
</com.nanlus.custom.CustomView>
</LinearLayout>
</RelativeLayout>
在这里需要解释一下,
xmlns:nanlus="http://schemas.android.com/apk/res/com.nanlus.custom"
nanlus为在xml中的前缀,com.nanlus.custom为包名
4、在Activity中,直接上代码
package com.nanlus.custom;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nanlus.BaseActivity;
import com.nanlus.custom.R;
import com.nanlus.custom.CustomView.CustomListener;
public class CustomActivity extends BaseActivity implements CustomListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((CustomView) this.findViewById(R.id.custom1)).setCustomListener(this);
}
@Override
public void onCuscomClick(View v, int custom_id) {
switch (custom_id) {
case 1:
Toast.makeText(this, "hello !!!", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
‘贰’ 如何在android studio中实现自定义view
一、首先新建一个项目,项目及名称自拟。
二、在app上点击右键->new->Mole 选择Android library。
三、在topbar下的values中新建一个attrs.xml文件,用来存放自定义view的属性。
4.在topbar下实现view。
5.上面两部做完后就是引用这个view,这里需要注意的是要在主app的build.gradle中添加引用如下:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':topbar')
}
topbar就是要使用的moudle,切记添加引用。然后就可以使用了。
6.要想使用自定义view中的属性的话任然需要添加xmlns:custom="schemas.android.com/apk/res-auto",前面加上http。
在这里还要注意命名空间也就是xustom之前一定不能定义过,否则重复的话就无法使用。
‘叁’ 怎样在Android Menu item中使用自定义View
1.自定义属性:attrs.xml
2.MenuItemView.java源码:
package com.dandy.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import com.lingyun.switchbutton.R;
/**
* 设置,菜单中的布局项
* 默认控件是纵向居中显示,所有paddingTop和paddingBottom在这没有作用
* Created by dandy on 2016/4/14.
*/
public class MenuItemView extends View{
private static final String TAG = "MenuItemView";
/**默认是按下状态的最小值**/
private static final long PRESSED_TIMEOUT = 10;
/**默认控件距离边界的大小**/
private static final int PADDING_DEFAULT = 18;
/**默认控件的高**/
private static final int HEIGHT_DEFAULT = 50;
/**文字绘制时默认大小**/
private static final int TEXTSZIE_DEFAULT = 14;
/**尾部箭头图标大小**/
private static final int ARROW_SIZE = 13;
/***SwitchButton默认宽*/
private static final int SWITCHBUTTON_WIDTH = 50;
/***SwitchButton默认高*/
private static final int SWITCHBUTTON_HEIGHT = 28;
/**头标**/
private Drawable headerDrawable;
/**头标宽**/
private int headerDrawableWidth;
/**头标高**/
private int headerDrawableHeight;
/**距离左边缘的距离**/
private int paddingLeft;
/**距离右边缘的距离**/
private int paddingRight;
/**绘制头标时,画布在Y轴的绘制偏移量**/
private float headerDrawableStartDrawY;
/**文字与图片间的距离**/
private int drawablePadding = -1;
/**头部文字提示**/
private String textHeader;
/**文字颜色**/
private int textHeaderColor = Color.parseColor("#5a5a5a");
/**文字大小**/
private int textSize = -1;
/**文字绘制时,画布在Y轴的绘制偏移量**/
private float textStartDrawY;
/**绘制文字的画笔**/
private Paint textPaint;
/** 尾部 > 图片**/
private Drawable arrowDrawable;
/**尾部 > 大小**/
private int arrowSize = -1;
/** > 绘制的X轴偏移量**/
private float arrowStartDrawX;
/** > 绘制的Y轴偏移量**/
private float arrowStartDrawY;
/**footerDrawable != null 时,绘制的时候是否按照原图片大小绘制**/
private boolean arrowWropToSelf = true;
/**尾部宽**/
private int arrowDrawableWidth;
/**尾部高**/
private int arrowDrawableHeight;
/**绘制arrow画笔**/
private Paint arrowPaint;
/**arrowPaint 颜色**/
private int arrowColor = Color.parseColor("#5a5a5a");
private DisplayMetrics dm;
/*以下是绘制SwitchButton所用到的参数*/
private Style style = Style.CUSTOM_ITEM;
/**默认宽**/
private int switchButtonWidth = -1;
/**默认高**/
private int switchButtonHeight = -1;
private static final long DELAYDURATION = 10;
/**开启颜色**/
private int onColor = Color.parseColor("#4ebb7f");
/**关闭颜色**/
private int offColor = Color.parseColor("#dadbda");
/**灰色带颜色**/
private int areaColor = Color.parseColor("#dadbda");
/**手柄颜色**/
private int handlerColor = Color.parseColor("#ffffff");
/**边框颜色**/
private int borderColor = offColor;
/**开关状态**/
private boolean toggleOn = false;
/**边框宽**/
private int borderWidth = 2;
/**纵轴中心**/
private float centerY;
/**按钮水平方向开始、结束的位置**/
private float startX,endX;
/**手柄x轴方向最小、最大值**/
private float handlerMinX,handlerMaxX;
/**手柄大小**/
private int handlerSize;
/**手柄在x轴的坐标位置**/
private float handlerX;
/**关闭时内部灰色带宽度**/
private float areaWidth;
/**是否使用动画效果**/
private boolean animate = true;
/**是否默认处于打开状态**/
private boolean defaultOn = true;
/**按钮半径**/
private float radius;
/**整个switchButton的区域**/
private RectF switchRectF = new RectF();
/**绘制switchButton的画笔**/
private Paint switchPaint;
private OnToggleChangedListener mListener;
private Handler mHandler = new Handler();
private double currentDelay;
private float downX = 0;
/**switchButton在X轴绘制的偏移量**/
private float switchButtonDrawStartX;
/**switchButton在Y轴绘制的偏移量**/
private float switchButtonDrawStartY;
/**分割线,默认在底部绘制**/
private Drawable dividerr;
/**分割线绘制的宽**/
private int dividerWidth = 2;
/**是否需要绘制分割线**/
private boolean dividerVisibilty = true;
/**触摸事件是否完成**/
private boolean touchDownEnd = false;
public MenuItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setup(attrs);
}
public MenuItemView(Context context, AttributeSet attrs) {
super(context, attrs);
setup(attrs);
}
/**
* 初始化控件,获取相关的控件属性
* @param attrs
*/
private void setup(AttributeSet attrs){
dm = Resources.getSystem().getDisplayMetrics();
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MenuItemView);
if(typedArray != null){
int count = typedArray.getIndexCount();
for(int i = 0;i < count;i++){
int attr = typedArray.getIndex(i);
switch (attr){
case R.styleable.MenuItemView_headerDrawable:
headerDrawable = typedArray.getDrawable(attr);
break;
case R.styleable.MenuItemView_drawPadding:
drawablePadding = typedArray.getDimensionPixelSize(attr,drawablePadding);
break;
case R.styleable.MenuItemView_textHeader:
textHeader = typedArray.getString(attr);
break;
case R.styleable.MenuItemView_textHeaderColor:
textHeaderColor = typedArray.getColor(attr, textHeaderColor);
break;
case R.styleable.MenuItemView_textSize:
textSize = typedArray.getDimensionPixelSize(attr, textSize);
break;
case R.styleable.MenuItemView_arrowDrawable:
arrowDrawable = typedArray.getDrawable(attr);
break;
case R.styleable.MenuItemView_arrowSize:
arrowSize = typedArray.getDimensionPixelSize(attr, arrowSize);
break;
case R.styleable.MenuItemView_arrowWropToSelf:
arrowWropToSelf = typedArray.getBoolean(attr, true);
break;
case R.styleable.MenuItemView_arrowColor:
arrowColor = typedArray.getColor(attr, arrowColor);
break;
case R.styleable.MenuItemView_onColor:
onColor = typedArray.getColor(attr, onColor);
break;
case R.styleable.MenuItemView_offColor:
borderColor = offColor = typedArray.getColor(attr,offColor);
break;
case R.styleable.MenuItemView_areaColor:
areaColor = typedArray.getColor(attr, areaColor);
break;
case R.styleable.MenuItemView_handlerColor:
handlerColor = typedArray.getColor(attr, handlerColor);
break;
case R.styleable.MenuItemView_bordeWidth:
borderWidth = typedArray.getColor(attr, borderWidth);
break;
case R.styleable.MenuItemView_animate:
animate = typedArray.getBoolean(attr, animate);
break;
case R.styleable.MenuItemView_defaultOn:
defaultOn = typedArray.getBoolean(attr, defaultOn);
break;
case R.styleable.MenuItemView_Style:
style = Style.getValue(typedArray.getInt(attr, Style.CUSTOM_ITEM.ordinal()));
break;
case R.styleable.MenuItemView_switchButtonWidth:
switchButtonWidth = typedArray.getDimensionPixelOffset(attr, switchButtonWidth);
break;
case R.styleable.MenuItemView_switchButtonHeight:
switchButtonHeight = typedArray.getDimensionPixelOffset(attr, switchButtonHeight);
break;
case R.styleable.MenuItemView_dividerr:
dividerr = typedArray.getDrawable(attr);
break;
case R.styleable.MenuItemView_dividerWidth:
dividerWidth = typedArray.getDimensionPixelOffset(attr,dividerWidth);
break;
case R.styleable.MenuItemView_dividerVisibilty:
dividerVisibilty = typedArray.getBoolean(attr,dividerVisibilty);
break;
}
}
typedArray.recycle();
}
‘肆’ android自定义view要怎么使用
视图,凡事能被用户看到的小控件都是一种view,也可以自定义view
‘伍’ Android开发 自定义View
Android自定义View实现很简单:
1、继承View,重写构造函数、onDraw,(onMeasure)等函数。
2、如果自定义的View需要有自定义的属性,需要在values下建立attrs.xml。在其中定义你的属性。
3、在使用到自定义View的xml布局文件中需要加入xmlns:前缀="http://schemas.android.com/apk/res/你的自定义View所在的包路径".
4、在使用自定义属性的时候,使用前缀:属性名,如my:textColor="#FFFFFFF"。
实例:
自定义TextView类:
复制代码
package com.zst.service.component;
import com.example.hello_wangle.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MyTextView extends TextView {
//不能在布局文件中使用
public MyTextView(Context context) {
super(context);
}
//布局文件中用到此构造函数
‘陆’ android 自定义view怎么做能提高效率
自定义view一般要调用里面的onDraw()方法,提高效率个人认为,主要是图片加载释放的一些处理很重要。比如,有些图可以在构造函数里加载,有些可以根据具体要求在onDraw判断一下在加载。这样就避免了有些功能不需要上来就加载图,但是你上来就加载大图,很影响效率。在一个就是及时释放相应图片了。
‘柒’ android开发怎么用自定义view类的方法
建一个新的class
extends
View
里面的方法自定义
这就是自定义view控件
引用的时候
在布局里
<包名.刚才建的类名
其他属性>
包名.刚才建的类名
‘捌’ android怎么自定义view
{
publicCustomTextview(Contextcontext){
this(context,null);
}
publicCustomTextview(Contextcontext,AttributeSetattrs){
this(context,attrs,com.android.internal.R.attr.textViewStyle);
}
publicCustomTextview(Contextcontext,AttributeSetattrs,intdefStyleAttr){
super(context,attrs,defStyleAttr);
//setText("Fuckme");
}
直接可以在xml布局文件中,调用。
‘玖’ android的自定义View的实现原理哪位能给我个思路呢。谢谢。
如果说要按类型来划分的话,自定义View的实现方式大概可以分为三种,自绘控件、组合控件、以及继承控件。那么下面我们就来依次学习一下,每种方式分别是如何自定义View的。
一、自绘控件
自绘控件的意思就是,这个View上所展现的内容全部都是我们自己绘制出来的。绘制的代码是写在onDraw()方法中的,而这部分内容我们已经在Android视图绘制流程完全解析,带你一步步深入了解View(二)中学习过了。
下面我们准备来自定义一个计数器View,这个View可以响应用户的点击事件,并自动记录一共点击了多少次。新建一个CounterView继承自View,代码如下所示:
<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffcb05">
<Button
android:id="@+id/button_left"
android:layout_width="60dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:background="@drawable/back_button"
android:text="Back"
android:textColor="#fff"/>
<TextView
android:id="@+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="ThisisTitle"
android:textColor="#fff"
android:textSize="20sp"/>
</RelativeLayout>
在这个布局文件中,我们首先定义了一个RelativeLayout作为背景布局,然后在这个布局里定义了一个Button和一个TextView,Button就是标题栏中的返回按钮,TextView就是标题栏中的显示的文字。
接下来创建一个TitleView继承自FrameLayout,代码如下所示:
{
privateButtonleftButton;
privateTextViewtitleText;
publicTitleView(Contextcontext,AttributeSetattrs){
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
titleText=(TextView)findViewById(R.id.title_text);
leftButton=(Button)findViewById(R.id.button_left);
leftButton.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
((Activity)getContext()).finish();
}
});
}
publicvoidsetTitleText(Stringtext){
titleText.setText(text);
}
publicvoidsetLeftButtonText(Stringtext){
leftButton.setText(text);
}
(OnClickListenerl){
leftButton.setOnClickListener(l);
}
}
TitleView中的代码非常简单,在TitleView的构建方法中,我们调用了LayoutInflater的inflate()方法来加载刚刚定义的title.xml布局,这部分内容我们已经在Android LayoutInflater原理分析,带你一步步深入了解View(一)这篇文章中学习过了。
接下来调用findViewById()方法获取到了返回按钮的实例,然后在它的onClick事件中调用finish()方法来关闭当前的Activity,也就相当于实现返回功能了。
另外,为了让TitleView有更强地扩展性,我们还提供了setTitleText()、setLeftButtonText()、setLeftButtonListener()等方法,分别用于设置标题栏上的文字、返回按钮上的文字、以及返回按钮的点击事件。
到了这里,一个自定义的标题栏就完成了,那么下面又到了如何引用这个自定义View的部分,其实方法基本都是相同的,在布局文件中添加如下代码:
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.customview.TitleView
android:id="@+id/title_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.example.customview.TitleView>
</RelativeLayout>
这样就成功将一个标题栏控件引入到布局文件中了,运行一下程序。
现在点击一下Back按钮,就可以关闭当前的Activity了。如果你想要修改标题栏上显示的内容,或者返回按钮的默认事件,只需要在Activity中通过findViewById()方法得到TitleView的实例,然后调用setTitleText()、setLeftButtonText()、setLeftButtonListener()等方法进行设置就OK了。
‘拾’ Android自定义控件CustomView,构造函数的参数context是怎么获取的
很明显,这个context是在调用构造函数的时候传递进来的。
以两个参数的构造函数为例,这个一般是在xml使用该控件后,解析xml时会调用构造方法。
那么这个时候传的context怎么来的呢?从父类传过来的,父类呢,也是从父类的父类传过来的,顶层父类是Decorview,那么看看Decorview的context怎么来的。
上图ActivityThread.java里的一个方法。
创建activity实例之前,我们会先创建context,而这个context实际上就是new 了一个ContextImpl。然后和activity绑定。所以getContext实际上就是一个ContextImpl实例。