Chinaunix首页 | 论坛 | 博客
  • 博客访问: 640178
  • 博文数量: 171
  • 博客积分: 2246
  • 博客等级: 大尉
  • 技术积分: 1574
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-31 11:45
文章分类

全部博文(171)

文章存档

2018年(3)

2017年(4)

2015年(1)

2014年(20)

2013年(57)

2012年(86)

分类: 嵌入式

2012-07-30 16:46:03

继承View,实现自己想要的组件,那么需要使用到setMeasuredDimension这个方法,这个方法决定了当前View的大小,请看代码:

View的代码:

Java代码  收藏代码
  1. package cc.mdev.test;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Canvas;  
  5. import android.graphics.Color;  
  6. import android.text.TextPaint;  
  7. import android.util.AttributeSet;  
  8. import android.util.Log;  
  9. import android.view.View;  
  10.   
  11. public class MyScrollView extends View {  
  12.   
  13. public MyScrollView(Context context, AttributeSet attrs) {  
  14. super(context, attrs);  
  15. }  
  16.   
  17. public MyScrollView(Context context) {  
  18. super(context);  
  19. }  
  20. @Override  
  21. protected void onDraw(Canvas canvas) {  
  22. TextPaint paint = new TextPaint();  
  23. paint.setAntiAlias(true);  
  24. canvas.drawColor(Color.GRAY);  
  25. for (int i = 10; i < 500; i++) {  
  26. canvas.drawText("This is the scroll text."10, i, paint);  
  27. i = i+15;  
  28. }  
  29. }  
  30.   
  31. @Override  
  32. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  33. String tag="onMeasure";  
  34. Log.e(tag, "Scroll View on measure...");  
  35. setMeasuredDimension(200800);  
  36. }  
  37.   
  38. @Override  
  39. protected void onScrollChanged(int l, int t, int oldl, int oldt) {  
  40. String tag = "onScrollChanged";  
  41. Log.e(tag, "Scroll....");  
  42. super.onScrollChanged(l, t, oldl, oldt);  
  43. }  
  44. }  

布局文件:

Xml代码  收藏代码
  1. xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="" 
  3.       android:orientation="vertical" 
  4.       android:layout_width="fill_parent" 
  5.       android:layout_height="fill_parent" 
  6.       android:background="#fff" > 

  7. <Button android:text="Button01" 
  8. android:id="@+id/Button01" 
  9. android:layout_width="wrap_content" 
  10. android:layout_height="wrap_content">
  11. Button> 

  12. <ScrollView android:layout_width="fill_parent" 
  13.     android:layout_height="fill_parent"> 
  14. <cc.mdev.test.MyScrollView android:layout_width="wrap_content" 
  15.        android:layout_height="wrap_content"/> 
  16. ScrollView> 

  17. LinearLayout>   
 


效果就是自定义视图的大小为
200, 800,并且放入到ScrollView中,ScrollView会启作用,如果不使用setMeasuredDimension这个方法,那么ScrollView不会有作用。

来源:

阅读(962) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~