1. 程式人生 > >Android View中的setMeasuredDimension方法

Android View中的setMeasuredDimension方法

繼承View,實現自己想要的元件,那麼需要使用到setMeasuredDimension這個方法,這個方法決定了當前View的大小,請看程式碼:

View的程式碼:

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




佈局檔案:

Xml程式碼  收藏程式碼
  1. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#fff" > <Button android:text="Button01" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent"> <cc.mdev.test.MyScrollView android:layout_width="wrap_content" android:layout_height="wrap_content"/> </ScrollView> </LinearLayout>   



效果就是自定義檢視的大小為
200, 800,並且放入到ScrollView中,ScrollView會啟作用,如果不使用setMeasuredDimension這個方法,那麼
ScrollView不會有作用。