自定義View的實現方式大概可以分為三種,自繪控件、組合控件、以及繼承控件。本文將介紹自繪控件的用法。自繪控件的意思是,這個控件上的內容是用onDraw函數繪制出來的。關於onDraw函數的介紹可參看 Android視圖繪制流程完全解析,帶你一步步深入了解View(二) 。
例子1:在layout文件中使用自繪控件
出處:http://blog.csdn.net/guolin_blog/article/details/17357967
下面我們准備來自定義一個計數器View,這個View可以響應用戶的點擊事件,並自動記錄一共點擊了多少次。新建一個CounterView繼承自View,代碼如下所示:
public class CounterView extends View implements OnClickListener { private Paint mPaint; private Rect mBounds; private int mCount; public CounterView(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBounds = new Rect(); setOnClickListener(this); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint.setColor(Color.BLUE); canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint); mPaint.setColor(Color.YELLOW); mPaint.setTextSize(30); String text = String.valueOf(mCount); mPaint.getTextBounds(text, 0, text.length(), mBounds); float textWidth = mBounds.width(); float textHeight = mBounds.height(); canvas.drawText(text, getWidth() / 2 - textWidth / 2, getHeight() / 2 + textHeight / 2, mPaint); } @Override public void onClick(View v) { mCount++; invalidate(); } }
可以看到,首先我們在CounterView的構造函數中初始化了一些數據,並給這個View的本身注冊了點擊事件,這樣當CounterView被點擊的時候,onClick()方法就會得到調用。而onClick()方法中的邏輯就更加簡單了,只是對mCount這個計數器加1,然后調用invalidate()方法。通過 Android視圖狀態及重繪流程分析,帶你一步步深入了解View(三) 這篇文章的學習我們都已經知道,調用invalidate()方法會導致視圖進行重繪,因此onDraw()方法在稍后就將會得到調用。
在布局文件中加入如下代碼:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.customview.CounterView android:layout_width="100dp" android:layout_height="100dp" android:layout_centerInParent="true" /> </RelativeLayout>
可以看到,這里我們將CounterView放入了一個RelativeLayout中。注意,自定義的View在使用的時候一定要寫出完整的包名,不然系統將無法找到這個View。
例子2:通過實例化對象的方式使用自定義控件
出處:http://blog.csdn.net/ameyume/article/details/6031024
Android繪圖操作,通過繼承View實現,在onDraw函數中實現繪圖。
下面是一個簡單的例子:
public class AndroidTest extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyView mv = new MyView(this); setContentView(mv); } public class MyView extends View { MyView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); // 首先定義一個paint Paint paint = new Paint(); // 繪制矩形區域-實心矩形 // 設置顏色 paint.setColor(Color.BLUE); // 設置樣式-填充 paint.setStyle(Style.FILL); // 繪制一個矩形 canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), paint); // 繪空心矩形 // 設置顏色 paint.setColor(Color.RED); // 設置樣式-空心矩形 paint.setStyle(Style.STROKE); // 繪制一個矩形 canvas.drawRect(new Rect(10, 10, 100, 30), paint); // 繪文字 // 設置顏色 paint.setColor(Color.GREEN); // 繪文字 canvas.drawText("Hello", 10, 50, paint); // 繪圖 // 從資源文件中生成位圖 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon); // 繪圖 canvas.drawBitmap(bitmap, 10, 60, paint); } } }