1、重写一个View。
引用一下网上的一个例子http://labs.ywlx.net/?p=284 ,代码如下:
public class RotateTextView extends TextView { private static final String NAMESPACE = “http://www.ywlx.net/apk/res/easymobi”; private static final String ATTR_ROTATE = “rotate”; private static final int DEFAULTVALUE_DEGREES = 0; private int degrees ; public RotateTextView(Context context, AttributeSet attrs) { super(context, attrs); degrees = attrs.getAttributeIntValue(NAMESPACE, ATTR_ROTATE, DEFAULTVALUE_DEGREES); } @Override protected void onDraw(Canvas canvas) { canvas.rotate(degrees,getMeasuredWidth()/2,getMeasuredHeight()/2); super.onDraw(canvas); } }
使用自定义RotateTextView如下:
<cn.easymobi.application.memorytest.RotateTextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:padding=”8dip” android:gravity=”center” android:id=”@+id/tvBottom_color” android:textSize=”15dip” android:textColor=”@color/black” easymobi:rotate=”10″ android:layout_marginTop=”468dip” />
个人觉得这个例子挺不错的,简单易懂,而且涉及的内容比较单一。需要更详细的讲解看文章http://labs.ywlx.net/?p=284 。
2、重写一个ViewGroup。
再次引用网上的一个例子http://blog.youkuaiyun.com/arui319/article/details/5868466 ,代码如下:
public class MyViewGroup extends ViewGroup { public MyViewGroup(Context context) { super(context); this.initOtherComponent(context); } private void initOtherComponent(Context context) { Button aBtn = new Button(context); // set id 1 aBtn.setId(1); aBtn.setText("a btn"); this.addView(aBtn); Button bBtn = new Button(context); // set id 2 bBtn.setId(2); bBtn.setText("b btn"); this.addView(bBtn); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); switch (child.getId()) { case 1: // 1 is aBtn Log.d("MyViewGroup", "btn1 setting"); child.setVisibility(View.VISIBLE); child.measure(r - l, b - t); child.layout(0, 0, child.getMeasuredWidth(), child .getMeasuredHeight()); break; case 2: // 2 is bBtn Log.d("MyViewGroup", "btn2 setting"); child.setVisibility(View.VISIBLE); child.measure(r - l, b - t); child.layout(0, 50, child.getMeasuredWidth(), child .getMeasuredHeight() + 50); break; default: // } } } }
这个例子主要是说明layout 和Measure的使用。
3、两个例子的总结。
重写一个view一般情况下只需要重写OnDraw方法。那么什么时候需要重写OnMeasure、OnLayout、OnDraw方法呢,这个问题只要把这几个方法的功能弄清楚你就应该知道怎么做了。在此我也简单的讲一下(描述不正确请拍砖,欢迎交流)。
①如果需要改变View绘制的图像,那么需要重写OnDraw方法。(这也是最常用的重写方式。)
②如果需要改变view的大小,那么需要重写OnMeasure方法。
③如果需要改变View的(在父控件的)位置,那么需要重写OnLayout方法。
④根据上面三种不同的需要你可以组合出多种重写方案,你懂的。