android 自定义控件的几种形式
来源:互联网 发布:直播app数据库设计 编辑:程序博客网 时间:2024/05/21 19:25
简单来说自定义控件就是继承自android api里的view 或者 viewgroup及其子类,根据需要重写相关方法来实现满足自定义显示和交互的控件。
如果说要按类型来划分的话,自定义View的实现方式大概可以分为三种,自绘控件、组合控件、以及继承控件。
一、自绘控件
1.自定义View
自定义View我们大部分时候只需重写两个函数:onMeasure()、onDraw()。onMeasure负责对当前View的尺寸进行测量,onDraw负责把当前这个View绘制出来。当然了,你还得写至少写2个构造函数:
public MyView(Context context) { super(context);}public MyView(Context context, AttributeSet attrs) { super(context, attrs); }
onMeasure
//重写方法protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) //根据参数判断测量模式和数据int widthMode = MeasureSpec.getMode(widthMeasureSpec);int widthSize = MeasureSpec.getSize(widthMeasureSpec);
测量模式 表示意思
UNSPECIFIED 父容器没有对当前View有任何限制,当前View可以任意取尺寸
EXACTLY 当前的尺寸就是当前View应该取的尺寸
AT_MOST 当前尺寸是当前View能取的最大尺寸
match_parent—>EXACTLY。match_parent就是要利用父View给我们提供的所有剩余空间,而父View剩余空间是确定的,也就是这个测量模式的整数里面存放的尺寸。
wrap_content—>AT_MOST。就是我们想要将大小设置为包裹我们的view内容,那么尺寸大小就是父View给我们作为参考的尺寸,只要不超过这个尺寸就可以啦,具体尺寸就根据我们的需求去设定。
固定尺寸(如100dp)—>EXACTLY。用户自己指定了尺寸大小,我们就不用再去干涉了,当然是以指定的大小为主啦。
将当前的View以正方形的形式显示,即要宽高相等,并且默认的宽高值为100像素。就可以这些编写:
private int getMySize(int defaultSize, int measureSpec) { int mySize = defaultSize; int mode = MeasureSpec.getMode(measureSpec); int size = MeasureSpec.getSize(measureSpec); switch (mode) { case MeasureSpec.UNSPECIFIED: {//如果没有指定大小,就设置为默认大小 mySize = defaultSize; break; } case MeasureSpec.AT_MOST: {//如果测量模式是最大取值为size //我们将大小取最大值,你也可以取其他值 mySize = size; break; } case MeasureSpec.EXACTLY: {//如果是固定的大小,那就不要去改变它 mySize = size; break; } } return mySize;}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = getMySize(100, widthMeasureSpec); int height = getMySize(100, heightMeasureSpec); if (width < height) { height = width; } else { width = height; } setMeasuredDimension(width, height);}
<com.hc.studyview.MyView android:layout_width="match_parent" android:layout_height="100dp" android:background="#ff0000" />
看看使用了我们自己定义的onMeasure函数后的效果:
onDraw
View显示一个圆形,我们在上面已经实现了宽高尺寸相等的基础上,继续往下做:
@Override protected void onDraw(Canvas canvas) { //调用父View的onDraw函数,因为View这个类帮我们实现了一些 // 基本的而绘制功能,比如绘制背景颜色、背景图片等 super.onDraw(canvas); int r = getMeasuredWidth() / 2;//也可以是getMeasuredHeight()/2,本例中我们已经将宽高设置相等了 //圆心的横坐标为当前的View的左边起始位置+半径 int centerX = getLeft() + r; //圆心的纵坐标为当前的View的顶部起始位置+半径 int centerY = getTop() + r; Paint paint = new Paint(); paint.setColor(Color.GREEN); //开始绘制 canvas.drawCircle(centerX, centerY, r, paint); }
自定义布局属性
首先我们需要在res/values/styles.xml文件(如果没有请自己新建)里面声明一个我们自定义的属性:
<resources> <!--name为声明的"属性集合"名,可以随便取,但是最好是设置为跟我们的View一样的名称--> <declare-styleable name="MyView"> <!--声明我们的属性,名称为default_size,取值类型为尺寸类型(dp,px等)--> <attr name="default_size" format="dimension" /> </declare-styleable></resources>
在布局文件里面使用:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:hc="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <com.hc.studyview.MyView android:layout_width="match_parent" android:layout_height="100dp" hc:default_size="100dp" /></LinearLayout>
在构造方法里面获取自定义属性值:
private int defalutSize; public MyView(Context context, AttributeSet attrs) { super(context, attrs); //第二个参数就是我们在styles.xml文件中的<declare-styleable>标签 //即属性集合的标签,在R文件中名称为R.styleable+name TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView); //第一个参数为属性集合里面的属性,R文件名称:R.styleable+属性集合名称+下划线+属性名称 //第二个参数为,如果没有设置这个属性,则设置的默认的值 defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100); //最后记得将TypedArray对象回收 a.recycle(); }
2.自定义ViewGroup
onMeasure ,实现测量子View大小以及设定ViewGroup的大小:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //将所有的子View进行测量,这会触发每个子View的onMeasure函数 //注意要与measureChild区分,measureChild是对单个view进行测量 measureChildren(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int childCount = getChildCount(); if (childCount == 0) {//如果没有子View,当前ViewGroup没有存在的意义,不用占用空间 setMeasuredDimension(0, 0); } else { //如果宽高都是包裹内容 if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) { //我们将高度设置为所有子View的高度相加,宽度设为子View中最大的宽度 int height = getTotleHeight(); int width = getMaxChildWidth(); setMeasuredDimension(width, height); } else if (heightMode == MeasureSpec.AT_MOST) {//如果只有高度是包裹内容 //宽度设置为ViewGroup自己的测量宽度,高度设置为所有子View的高度总和 setMeasuredDimension(widthSize, getTotleHeight()); } else if (widthMode == MeasureSpec.AT_MOST) {//如果只有宽度是包裹内容 //宽度设置为子View中宽度最大的值,高度设置为ViewGroup自己的测量值 setMeasuredDimension(getMaxChildWidth(), heightSize); } } } /*** * 获取子View中宽度最大的值 */ private int getMaxChildWidth() { int childCount = getChildCount(); int maxWidth = 0; for (int i = 0; i < childCount; i++) { View childView = getChildAt(i); if (childView.getMeasuredWidth() > maxWidth) maxWidth = childView.getMeasuredWidth(); } return maxWidth; } /*** * 将所有子View的高度相加 **/ private int getTotleHeight() { int childCount = getChildCount(); int height = 0; for (int i = 0; i < childCount; i++) { View childView = getChildAt(i); height += childView.getMeasuredHeight(); } return height; }
上面的onMeasure将子View测量好了,以及把自己的尺寸也设置好了,接下来我们去摆放子View:
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int count = getChildCount(); //记录当前的高度位置 int curHeight = t; //将子View逐个摆放 for (int i = 0; i < count; i++) { View child = getChildAt(i); int height = child.getMeasuredHeight(); int width = child.getMeasuredWidth(); //摆放子View,参数分别是子View矩形区域的左、上、右、下边 child.layout(l, curHeight, l + width, curHeight + height); curHeight += height; } }
其余步骤同自定义view。
二、组合控件
只是用系统原生的控件就好了,但我们可以将几个系统原生的控件组合到一起,这样创建出的控件就被称为组合控件。
//通过此方法加载而已LayoutInflater.from(context).inflate(R.layout.xxx, this);
//在构造方法中运行此方法public class TitleView extends FrameLayout { private Button leftButton; private TextView titleText; public TitleView(Context context, AttributeSet attrs) { 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(new OnClickListener() { @Override public void onClick(View v) { ((Activity) getContext()).finish(); } }); } public void setTitleText(String text) { titleText.setText(text); } public void setLeftButtonText(String text) { leftButton.setText(text); } public void setLeftButtonListener(OnClickListener l) { leftButton.setOnClickListener(l); }}
以上两步就完成了组合控件的开发,就能像其他控件一样使用了。
三、继承控件
去继承一个现有的控件,然后在这个控件上增加一些新的功能,就可以形成一个自定义的控件了。这种自定义控件的特点就是不仅能够按照我们的需求加入相应的功能,还可以保留原生控件的所有功能。
加入在ListView上滑动就可以显示出一个删除按钮,点击按钮就会删除相应数据的功能。
新建delete_button.xml文件,代码如下所示:
<?xml version="1.0" encoding="utf-8"?><Button xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/delete_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/delete_button" ></Button>
public class MyListView extends ListView implements OnTouchListener, OnGestureListener { private GestureDetector gestureDetector; private OnDeleteListener listener; private View deleteButton; private ViewGroup itemLayout; private int selectedItem; private boolean isDeleteShown; public MyListView(Context context, AttributeSet attrs) { super(context, attrs); gestureDetector = new GestureDetector(getContext(), this); setOnTouchListener(this); } public void setOnDeleteListener(OnDeleteListener l) { listener = l; } @Override public boolean onTouch(View v, MotionEvent event) { if (isDeleteShown) { itemLayout.removeView(deleteButton); deleteButton = null; isDeleteShown = false; return false; } else { return gestureDetector.onTouchEvent(event); } } @Override public boolean onDown(MotionEvent e) { if (!isDeleteShown) { selectedItem = pointToPosition((int) e.getX(), (int) e.getY()); } return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (!isDeleteShown && Math.abs(velocityX) > Math.abs(velocityY)) { deleteButton = LayoutInflater.from(getContext()).inflate( R.layout.delete_button, null); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { itemLayout.removeView(deleteButton); deleteButton = null; isDeleteShown = false; listener.onDelete(selectedItem); } }); itemLayout = (ViewGroup) getChildAt(selectedItem - getFirstVisiblePosition()); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); params.addRule(RelativeLayout.CENTER_VERTICAL); itemLayout.addView(deleteButton, params); isDeleteShown = true; } return false; } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } public interface OnDeleteListener { void onDelete(int index); }}
新建my_list_view_item.xml,代码如下所示:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:descendantFocusability="blocksDescendants" android:orientation="vertical" > <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_centerVertical="true" android:gravity="left|center_vertical" android:textColor="#000" /></RelativeLayout>
自定义adapter:
public class MyAdapter extends ArrayAdapter<String> { public MyAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = LayoutInflater.from(getContext()).inflate(R.layout.my_list_view_item, null); } else { view = convertView; } TextView textView = (TextView) view.findViewById(R.id.text_view); textView.setText(getItem(position)); return view; }}
使用控件:
<RelativeLayout xmlns: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.MyListView android:id="@+id/my_list_view" android:layout_width="match_parent" android:layout_height="wrap_content" > </com.example.customview.MyListView></RelativeLayout>
public class MainActivity extends Activity { private MyListView myListView; private MyAdapter adapter; private List<String> contentList = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initList(); myListView = (MyListView) findViewById(R.id.my_list_view); myListView.setOnDeleteListener(new OnDeleteListener() { @Override public void onDelete(int index) { contentList.remove(index); adapter.notifyDataSetChanged(); } }); adapter = new MyAdapter(this, 0, contentList); myListView.setAdapter(adapter); } private void initList() { contentList.add("Content Item 1"); contentList.add("Content Item 2"); contentList.add("Content Item 3"); contentList.add("Content Item 4"); contentList.add("Content Item 5"); contentList.add("Content Item 6"); contentList.add("Content Item 7"); contentList.add("Content Item 8"); contentList.add("Content Item 9"); contentList.add("Content Item 10"); contentList.add("Content Item 11"); contentList.add("Content Item 12"); contentList.add("Content Item 13"); contentList.add("Content Item 14"); contentList.add("Content Item 15"); contentList.add("Content Item 16"); contentList.add("Content Item 17"); contentList.add("Content Item 18"); contentList.add("Content Item 19"); contentList.add("Content Item 20"); }}
效果图如下:
- android 自定义控件的几种形式
- Dialog的几种形式 Android开发
- Android dialog的几种形式
- Android Toast的几种形式
- android动画的几种形式
- 自定义控件的形式与使用
- Android -- 几种保存成jpeg文件的形式
- Android利用WebView与h5交互的几种形式
- DDOS 的几种形式
- 封装的几种形式
- 数据传输的几种形式
- ListView的几种形式
- ListView的几种形式
- pooling的几种形式
- ReactNative 自定义Android原生模块的两种形式
- Android dialog 使用几种形式
- android的几种进度条控件描述
- android自定义view的几种方式
- [Algorithm] BST问题
- 使用Linq查询数据进行分页时遇到的性能问题
- java面试总结
- bzoj 3211: 花神游历各国 && bzoj 3038: 上帝造题的七分钟2
- Java并发编程二
- android 自定义控件的几种形式
- Textbook Ex.8.22
- MySQL设计原则
- Android 6.0动态权限和一些收获
- Session一致性架构设计
- 如何使用@Results,@Result
- C++拷贝构造函数
- 如何让TP框架的分页类输出美观一点
- 视觉里程计(一)