歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android編程動態創建視圖View的方法

Android編程動態創建視圖View的方法

日期:2017/3/1 11:14:56   编辑:Linux編程
在Android開發中,在Activity中關聯視圖View是一般使用setContentView方法,該方法一種參數是使用XML資源直接創建:setContentView (int layoutResID),指定layout中的一個XML的ID即可,這種方法簡單。另一個方法是setContentView(android.view.View),參數是指定一個視圖View對象,這種方法可以使用自定義的視圖類。

在一些場合中,需要對View進行一些定制處理,比如獲取到Canvas進行圖像繪制,需要重載View::onDraw方法,這時需要對View進行派生一個類,重載所需要的方法,然後使用setContentView(android.view.View)與Activity進行關聯,具體代碼舉例如下:

  1. public class temp extends Activity {
  2. /** 在Activity中關聯視圖view */
  3. @Override
  4. public void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(new DrawView(this));
  7. }
  8. /*自定義類*/
  9. private class DrawView extends View {
  10. private Paint paint;
  11. /**
  12. * Constructor
  13. */
  14. public DrawView(Context context) {
  15. super(context);
  16. paint = new Paint();
  17. // set's the paint's colour
  18. paint.setColor(Color.GREEN);
  19. // set's paint's text size
  20. paint.setTextSize(25);
  21. // smooth's out the edges of what is being drawn
  22. paint.setAntiAlias(true);
  23. }
  24. protected void onDraw(Canvas canvas) {
  25. super.onDraw(canvas);
  26. canvas.drawText("Hello World", 5, 30, paint);
  27. // if the view is visible onDraw will be called at some point in the
  28. // future
  29. invalidate();
  30. }
  31. }
  32. }

第二個例子,動態繪圖

  1. public class MyAndroidProjectActivity extends Activity {
  2. /** Called when the activity is first created. */
  3. /*
  4. public void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.main);
  7. }*/
  8. static int times = 1;
  9. /** Called when the activity is first created. */
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(new DrawView(this));
  14. }
  15. private class DrawView extends View {
  16. Paint vPaint = new Paint();
  17. private int i = 0;
  18. public DrawView(Context context) {
  19. super(context);
  20. }
  21. protected void onDraw(Canvas canvas) {
  22. super.onDraw(canvas);
  23. System.out.println("this run " + (times++) +" times!");
  24. // 設定繪圖樣式
  25. vPaint.setColor( 0xff00ffff ); //畫筆顏色
  26. vPaint.setAntiAlias( true ); //反鋸齒
  27. vPaint.setStyle( Paint.Style.STROKE );
  28. // 繪制一個弧形
  29. canvas.drawArc(new RectF(60, 120, 260, 320), 0, i, true, vPaint );
  30. // 弧形角度
  31. if( (i+=10) > 360 )
  32. i = 0;
  33. // 重繪, 再一次執行onDraw 程序
  34. invalidate();
  35. }
  36. }
  37. }
Copyright © Linux教程網 All Rights Reserved