zoukankan      html  css  js  c++  java
  • Android自己定义View的实现方法

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/17357967

    不知不觉中,带你一步步深入了解View系列的文章已经写到第四篇了。回想一下,我们一共学习了LayoutInflater的原理分析、视图的绘制流程、视图的状态及重绘等知识,算是把View中非常多重要的知识点都涉及到了。假设你还没有看过我前面的几篇文章,建议先去阅读一下。多了解一些原理方面的东西。

    之前我有承诺过。会在View这个话题上多写几篇博客,讲一讲View的工作原理。以及自己定义View的方法。如今前半部分的承诺已经如约兑现了。那么今天我就要来兑现后面部分的承诺,讲一讲自己定义View的实现方法,同一时候这也是带你一步步深入了解View系列的完结篇。

    一些接触Android不久的朋友对自己定义View都有一丝畏惧感,总感觉这是一个比較高级的技术,但事实上自己定义View并不复杂。有时候仅仅须要简单几行代码就能够完毕了。

    假设说要按类型来划分的话,自己定义View的实现方式大概能够分为三种,自绘控件、组合控件、以及继承控件。

    那么以下我们就来依次学习一下。每种方式各自是怎样自己定义View的。

    一、自绘控件

    自绘控件的意思就是,这个View上所展现的内容所有都是我们自己绘制出来的。

    绘制的代码是写在onDraw()方法中的,而这部分内容我们已经在 Android视图绘制流程全然解析,带你一步步深入了解View(二) 中学习过了。

    以下我们准备来自己定义一个计数器View。这个View能够响应用户的点击事件,并自己主动记录一共点击了多少次。新建一个CounterView继承自View,代码例如以下所看到的:

    [java] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. public class CounterView extends View implements OnClickListener {  
    2.   
    3.     private Paint mPaint;  
    4.       
    5.     private Rect mBounds;  
    6.   
    7.     private int mCount;  
    8.       
    9.     public CounterView(Context context, AttributeSet attrs) {  
    10.         super(context, attrs);  
    11.         mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);  
    12.         mBounds = new Rect();  
    13.         setOnClickListener(this);  
    14.     }  
    15.   
    16.     @Override  
    17.     protected void onDraw(Canvas canvas) {  
    18.         super.onDraw(canvas);  
    19.         mPaint.setColor(Color.BLUE);  
    20.         canvas.drawRect(00, getWidth(), getHeight(), mPaint);  
    21.         mPaint.setColor(Color.YELLOW);  
    22.         mPaint.setTextSize(30);  
    23.         String text = String.valueOf(mCount);  
    24.         mPaint.getTextBounds(text, 0, text.length(), mBounds);  
    25.         float textWidth = mBounds.width();  
    26.         float textHeight = mBounds.height();  
    27.         canvas.drawText(text, getWidth() / 2 - textWidth / 2, getHeight() / 2  
    28.                 + textHeight / 2, mPaint);  
    29.     }  
    30.   
    31.     @Override  
    32.     public void onClick(View v) {  
    33.         mCount++;  
    34.         invalidate();  
    35.     }  
    36.   
    37. }  
    能够看到。首先我们在CounterView的构造函数中初始化了一些数据,并给这个View的本身注冊了点击事件。这样当CounterView被点击的时候,onClick()方法就会得到调用。

    而onClick()方法中的逻辑就更加简单了。仅仅是对mCount这个计数器加1,然后调用invalidate()方法。

    通过Android视图状态及重绘流程分析,带你一步步深入了解View(三) 这篇文章的学习我们都已经知道。调用invalidate()方法会导致视图进行重绘。因此onDraw()方法在稍后就将会得到调用。

    既然CounterView是一个自绘视图,那么最基本的逻辑当然就是写在onDraw()方法里的了。以下我们就来细致看一下。

    这里首先是将Paint画笔设置为蓝色,然后调用Canvas的drawRect()方法绘制了一个矩形,这个矩形也就能够当作是CounterView的背景图吧。接着将画笔设置为黄色,准备在背景上面绘制当前的计数,注意这里先是调用了getTextBounds()方法来获取到文字的宽度和高度,然后调用了drawText()方法去进行绘制就能够了。

    这样,一个自己定义的View就已经完毕了,而且眼下这个CounterView是具备自己主动计数功能的。那么剩下的问题就是怎样让这个View在界面上显示出来了,事实上这也很easy,我们仅仅须要像使用普通的控件一样来使用CounterView就能够了。

    比方在布局文件里增加例如以下代码:

    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    2.     android:layout_width="match_parent"  
    3.     android:layout_height="match_parent" >  
    4.   
    5.     <com.example.customview.CounterView  
    6.         android:layout_width="100dp"  
    7.         android:layout_height="100dp"  
    8.         android:layout_centerInParent="true" />  
    9.   
    10. </RelativeLayout>  
    能够看到,这里我们将CounterView放入了一个RelativeLayout中,然后能够像使用普通控件来给CounterView指定各种属性。比方通过layout_width和layout_height来指定CounterView的宽高,通过android:layout_centerInParent来指定它在布局里居中显示。

    仅仅只是须要注意。自己定义的View在使用的时候一定要写出完整的包名,不然系统将无法找到这个View。

    好了,就是这么简单。接下来我们能够执行一下程序,并不停地点击CounterView,效果例如以下图所看到的。


    怎么样?是不是感觉自己定义View也并非什么高级的技术,简单几行代码就能够实现了。当然了,这个CounterView功能非常简陋,仅仅有一个计数功能,因此仅仅需几行代码就足够了,当你须要绘制比較复杂的View时,还是须要非常多技巧的。

    二、组合控件

    组合控件的意思就是,我们并不须要自己去绘制视图上显示的内容。而仅仅是用系统原生的控件就好了,但我们能够将几个系统原生的控件组合到一起,这样创建出的控件就被称为组合控件。

    举个样例来说。标题栏就是个非经常见的组合控件,非常多界面的头部都会放置一个标题栏,标题栏上会有个返回button和标题,点击button后就能够返回到上一个界面。那么以下我们就来尝试去实现这样一个标题栏控件。

    新建一个title.xml布局文件。代码例如以下所看到的:

    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="50dp"  
    5.     android:background="#ffcb05" >  
    6.   
    7.     <Button  
    8.         android:id="@+id/button_left"  
    9.         android:layout_width="60dp"  
    10.         android:layout_height="40dp"  
    11.         android:layout_centerVertical="true"  
    12.         android:layout_marginLeft="5dp"  
    13.         android:background="@drawable/back_button"  
    14.         android:text="Back"  
    15.         android:textColor="#fff" />  
    16.   
    17.     <TextView  
    18.         android:id="@+id/title_text"  
    19.         android:layout_width="wrap_content"  
    20.         android:layout_height="wrap_content"  
    21.         android:layout_centerInParent="true"  
    22.         android:text="This is Title"  
    23.         android:textColor="#fff"  
    24.         android:textSize="20sp" />  
    25.   
    26. </RelativeLayout>  

    在这个布局文件里,我们首先定义了一个RelativeLayout作为背景布局,然后在这个布局里定义了一个Button和一个TextView,Button就是标题栏中的返回button。TextView就是标题栏中的显示的文字。

    接下来创建一个TitleView继承自FrameLayout。代码例如以下所看到的:

    [java] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. public class TitleView extends FrameLayout {  
    2.   
    3.     private Button leftButton;  
    4.   
    5.     private TextView titleText;  
    6.   
    7.     public TitleView(Context context, AttributeSet attrs) {  
    8.         super(context, attrs);  
    9.         LayoutInflater.from(context).inflate(R.layout.title, this);  
    10.         titleText = (TextView) findViewById(R.id.title_text);  
    11.         leftButton = (Button) findViewById(R.id.button_left);  
    12.         leftButton.setOnClickListener(new OnClickListener() {  
    13.             @Override  
    14.             public void onClick(View v) {  
    15.                 ((Activity) getContext()).finish();  
    16.             }  
    17.         });  
    18.     }  
    19.   
    20.     public void setTitleText(String text) {  
    21.         titleText.setText(text);  
    22.     }  
    23.   
    24.     public void setLeftButtonText(String text) {  
    25.         leftButton.setText(text);  
    26.     }  
    27.   
    28.     public void setLeftButtonListener(OnClickListener l) {  
    29.         leftButton.setOnClickListener(l);  
    30.     }  
    31.   
    32. }  
    TitleView中的代码很easy。在TitleView的构建方法中。我们调用了LayoutInflater的inflate()方法来载入刚刚定义的title.xml布局,这部分内容我们已经在 Android LayoutInflater原理分析,带你一步步深入了解View(一) 这篇文章中学习过了。

    接下来调用findViewById()方法获取到了返回button的实例。然后在它的onClick事件中调用finish()方法来关闭当前的Activity,也就相当于实现返回功能了。

    另外,为了让TitleView有更强地扩展性,我们还提供了setTitleText()、setLeftButtonText()、setLeftButtonListener()等方法,分别用于设置标题栏上的文字、返回button上的文字、以及返回button的点击事件。

    到了这里。一个自己定义的标题栏就完毕了,那么以下又到了怎样引用这个自己定义View的部分。事实上方法基本都是同样的,在布局文件里加入例如以下代码:

    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    2.     xmlns:tools="http://schemas.android.com/tools"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent" >  
    5.   
    6.     <com.example.customview.TitleView  
    7.         android:id="@+id/title_view"  
    8.         android:layout_width="match_parent"  
    9.         android:layout_height="wrap_content" >  
    10.     </com.example.customview.TitleView>  
    11.   
    12. </RelativeLayout>  

    这样就成功将一个标题栏控件引入到布局文件里了,执行一下程序,效果例如以下图所看到的:


    如今点击一下Backbutton,就能够关闭当前的Activity了。假设你想要改动标题栏上显示的内容,或者返回button的默认事件。仅仅须要在Activity中通过findViewById()方法得到TitleView的实例。然后调用setTitleText()、setLeftButtonText()、setLeftButtonListener()等方法进行设置就OK了。

    三、继承控件

    继承控件的意思就是,我们并不须要自己重头去实现一个控件。仅仅须要去继承一个现有的控件,然后在这个控件上添加一些新的功能。就能够形成一个自己定义的控件了。

    这样的自己定义控件的特点就是不仅能够依照我们的需求添加对应的功能,还能够保留原生控件的全部功能。比方 Android PowerImageView实现。能够播放动画的强大ImageView 这篇文章中介绍的PowerImageView就是一个典型的继承控件。

    为了可以加深大家对这样的自己定义View方式的理解,以下我们再来编写一个新的继承控件。ListView相信每个Android程序猿都一定使用过,这次我们准备对ListView进行扩展。增加在ListView上滑动就行显示出一个删除button,点击button就会删除对应数据的功能。

    首先须要准备一个删除按钮的布局,新建delete_button.xml文件,代码例如以下所看到的:

    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. <?

      xml version="1.0" encoding="utf-8"?

      >  

    2. <Button xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:id="@+id/delete_button"  
    4.     android:layout_width="wrap_content"  
    5.     android:layout_height="wrap_content"  
    6.     android:background="@drawable/delete_button" >  
    7.   
    8. </Button>  
    这个布局文件非常easy,仅仅有一个button而已。而且我们给这个button指定了一张删除背景图。

    接着创建MyListView继承自ListView,这就是我们自己定义的View了,代码例如以下所看到的:

    [java] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. public class MyListView extends ListView implements OnTouchListener,  
    2.         OnGestureListener {  
    3.   
    4.     private GestureDetector gestureDetector;  
    5.   
    6.     private OnDeleteListener listener;  
    7.   
    8.     private View deleteButton;  
    9.   
    10.     private ViewGroup itemLayout;  
    11.   
    12.     private int selectedItem;  
    13.   
    14.     private boolean isDeleteShown;  
    15.   
    16.     public MyListView(Context context, AttributeSet attrs) {  
    17.         super(context, attrs);  
    18.         gestureDetector = new GestureDetector(getContext(), this);  
    19.         setOnTouchListener(this);  
    20.     }  
    21.   
    22.     public void setOnDeleteListener(OnDeleteListener l) {  
    23.         listener = l;  
    24.     }  
    25.   
    26.     @Override  
    27.     public boolean onTouch(View v, MotionEvent event) {  
    28.         if (isDeleteShown) {  
    29.             itemLayout.removeView(deleteButton);  
    30.             deleteButton = null;  
    31.             isDeleteShown = false;  
    32.             return false;  
    33.         } else {  
    34.             return gestureDetector.onTouchEvent(event);  
    35.         }  
    36.     }  
    37.   
    38.     @Override  
    39.     public boolean onDown(MotionEvent e) {  
    40.         if (!isDeleteShown) {  
    41.             selectedItem = pointToPosition((int) e.getX(), (int) e.getY());  
    42.         }  
    43.         return false;  
    44.     }  
    45.   
    46.     @Override  
    47.     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,  
    48.             float velocityY) {  
    49.         if (!isDeleteShown && Math.abs(velocityX) > Math.abs(velocityY)) {  
    50.             deleteButton = LayoutInflater.from(getContext()).inflate(  
    51.                     R.layout.delete_button, null);  
    52.             deleteButton.setOnClickListener(new OnClickListener() {  
    53.                 @Override  
    54.                 public void onClick(View v) {  
    55.                     itemLayout.removeView(deleteButton);  
    56.                     deleteButton = null;  
    57.                     isDeleteShown = false;  
    58.                     listener.onDelete(selectedItem);  
    59.                 }  
    60.             });  
    61.             itemLayout = (ViewGroup) getChildAt(selectedItem  
    62.                     - getFirstVisiblePosition());  
    63.             RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(  
    64.                     LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
    65.             params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);  
    66.             params.addRule(RelativeLayout.CENTER_VERTICAL);  
    67.             itemLayout.addView(deleteButton, params);  
    68.             isDeleteShown = true;  
    69.         }  
    70.         return false;  
    71.     }  
    72.   
    73.     @Override  
    74.     public boolean onSingleTapUp(MotionEvent e) {  
    75.         return false;  
    76.     }  
    77.   
    78.     @Override  
    79.     public void onShowPress(MotionEvent e) {  
    80.   
    81.     }  
    82.   
    83.     @Override  
    84.     public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,  
    85.             float distanceY) {  
    86.         return false;  
    87.     }  
    88.   
    89.     @Override  
    90.     public void onLongPress(MotionEvent e) {  
    91.     }  
    92.       
    93.     public interface OnDeleteListener {  
    94.   
    95.         void onDelete(int index);  
    96.   
    97.     }  
    98.   
    99. }  
    因为代码逻辑比較简单,我就没有加凝视。这里在MyListView的构造方法中创建了一个GestureDetector的实例用于监听手势。然后给MyListView注冊了touch监听事件。

    然后在onTouch()方法中进行推断,假设删除button已经显示了,就将它移除掉,假设删除button没有显示。就使用GestureDetector来处理当前手势。

    当手指按下时,会调用OnGestureListener的onDown()方法。在这里通过pointToPosition()方法来推断出当前选中的是ListView的哪一行。

    当手指高速滑动时。会调用onFling()方法。在这里会去载入delete_button.xml这个布局,然后将删除button加入到当前选中的那一行item上。注意。我们还给删除button加入了一个点击事件。当点击了删除button时就会回调onDeleteListener的onDelete()方法,在回调方法中应该去处理详细的删除操作。

    好了,自己定义View的功能到此就完毕了。接下来我们须要看一下怎样才干使用这个自己定义View。

    首先须要创建一个ListView子项的布局文件,新建my_list_view_item.xml。代码例如以下所看到的:

    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent"  
    5.     android:descendantFocusability="blocksDescendants"  
    6.     android:orientation="vertical" >  
    7.   
    8.     <TextView  
    9.         android:id="@+id/text_view"  
    10.         android:layout_width="wrap_content"  
    11.         android:layout_height="50dp"  
    12.         android:layout_centerVertical="true"  
    13.         android:gravity="left|center_vertical"  
    14.         android:textColor="#000" />  
    15.   
    16. </RelativeLayout>  
    然后创建一个适配器MyAdapter。在这个适配器中去载入my_list_view_item布局,代码例如以下所看到的:
    [java] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. public class MyAdapter extends ArrayAdapter<String> {  
    2.   
    3.     public MyAdapter(Context context, int textViewResourceId, List<String> objects) {  
    4.         super(context, textViewResourceId, objects);  
    5.     }  
    6.   
    7.     @Override  
    8.     public View getView(int position, View convertView, ViewGroup parent) {  
    9.         View view;  
    10.         if (convertView == null) {  
    11.             view = LayoutInflater.from(getContext()).inflate(R.layout.my_list_view_item, null);  
    12.         } else {  
    13.             view = convertView;  
    14.         }  
    15.         TextView textView = (TextView) view.findViewById(R.id.text_view);  
    16.         textView.setText(getItem(position));  
    17.         return view;  
    18.     }  
    19.   
    20. }  
    到这里就基本已经完工了,以下在程序的主布局文件中面引入MyListView这个控件。例如以下所看到的:
    [html] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    2.     xmlns:tools="http://schemas.android.com/tools"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent" >  
    5.   
    6.     <com.example.customview.MyListView  
    7.         android:id="@+id/my_list_view"  
    8.         android:layout_width="match_parent"  
    9.         android:layout_height="wrap_content" >  
    10.     </com.example.customview.MyListView>  
    11.   
    12. </RelativeLayout>  
    最后在Activity中初始化MyListView中的数据。并处理了onDelete()方法的删除逻辑。代码例如以下所看到的:
    [java] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. public class MainActivity extends Activity {  
    2.   
    3.     private MyListView myListView;  
    4.   
    5.     private MyAdapter adapter;  
    6.   
    7.     private List<String> contentList = new ArrayList<String>();  
    8.   
    9.     @Override  
    10.     protected void onCreate(Bundle savedInstanceState) {  
    11.         super.onCreate(savedInstanceState);  
    12.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
    13.         setContentView(R.layout.activity_main);  
    14.         initList();  
    15.         myListView = (MyListView) findViewById(R.id.my_list_view);  
    16.         myListView.setOnDeleteListener(new OnDeleteListener() {  
    17.             @Override  
    18.             public void onDelete(int index) {  
    19.                 contentList.remove(index);  
    20.                 adapter.notifyDataSetChanged();  
    21.             }  
    22.         });  
    23.         adapter = new MyAdapter(this0, contentList);  
    24.         myListView.setAdapter(adapter);  
    25.     }  
    26.   
    27.     private void initList() {  
    28.         contentList.add("Content Item 1");  
    29.         contentList.add("Content Item 2");  
    30.         contentList.add("Content Item 3");  
    31.         contentList.add("Content Item 4");  
    32.         contentList.add("Content Item 5");  
    33.         contentList.add("Content Item 6");  
    34.         contentList.add("Content Item 7");  
    35.         contentList.add("Content Item 8");  
    36.         contentList.add("Content Item 9");  
    37.         contentList.add("Content Item 10");  
    38.         contentList.add("Content Item 11");  
    39.         contentList.add("Content Item 12");  
    40.         contentList.add("Content Item 13");  
    41.         contentList.add("Content Item 14");  
    42.         contentList.add("Content Item 15");  
    43.         contentList.add("Content Item 16");  
    44.         contentList.add("Content Item 17");  
    45.         contentList.add("Content Item 18");  
    46.         contentList.add("Content Item 19");  
    47.         contentList.add("Content Item 20");  
    48.     }  
    49.   
    50. }  
    这样就把整个样例的代码都完毕了。如今执行一下程序,会看到MyListView能够像ListView一样,正常显示全部的数据。可是当你用手指在MyListView的某一行上高速滑动时,就会有一个删除button显示出来。例如以下图所看到的:
    点击一下删除button就能够将第6行的数据删除了。此时的MyListView不仅保留了ListView原生的全部功能。还添加了一个滑动进行删除的功能。确实是一个不折不扣的继承控件。
    到了这里。我们就把自己定义View的几种实现方法所有讲完了,尽管每一个样例都非常easy,可是万变不离其宗,复杂的View也是由这些简单的原理堆积出来的。经过了四篇文章的学习,相信每一个人对View的理解都已经较为深入了,那么带你一步步深入了解View系列的文章就到此结束,感谢大家有耐心看到最后。

  • 相关阅读:
    我的大学学习之路
    拉勾上的一道题目
    python中文处理之encode/decode函数
    几个容易出错的css盒子模型细节
    洗牌算法shuffle
    判断正整数是否对称
    一种快速求fibonacci第n个数的算法
    利用正则表达式作为string.split seprator
    docker部分命令
    idea上传项目到GitHub
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7225198.html
Copyright © 2011-2022 走看看