2013-08-25 13 views
1

我有一個存儲在XML佈局中的自定義視圖。 XML佈局是我的活動視圖。我可以從我的Activity中引用XML Layout中的Custom View,就像您使用任何Android Widget一樣。然後,我可以獲得工作正常的onTouch偵聽器。我想要做的是引用我的自定義視圖中的一個方法,這將使我可以在畫布上繪製。我通過使用下面的代碼綁定,但沒有成功。任何幫助將非常感激。 PS我的代碼比這更多,我剛剛列出了我認爲最有必要的東西。來自活動的自定義視圖中的Android參考方法

public class DrawView extends View { 

     public Canvas; 
     public Paint textPaint = new Paint() 

     public DrawView(Context context, AttributeSet attributeSet) { 
     super.DrawView(context attributeSet) 
     textPaint.setColor(getResources().getColor(R.color.text)); 
     } 

     @Override 
     onDraw(Canvas canvas) { 
      mCanvas = canvas; 
     } 

     public void drawText() { 
      mCanvas.drawText("text", 100, 100, textPaint); 
     } 
} 

MainActivity:

public class MainActivity extends Activity { 
    DrawView mDrawView; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.sch_main); 

     //Get Handlers To DrawView 
     mDrawView = (DrawView) findViewById(R.id.draw); 

     //Get onTouch from DrawView 
     mDrawView.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View view, MotionEvent motionEvent) { 
       if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { 

       } 
       else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) { 

       } 
       else if (motionEvent.getAction() == MotionEvent.ACTION_UP) { 
        mDrawView.drawText(); 
       } 
       return false; 
      } 
     }); 

    } 
} 

佈局:

<LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical"> 

    <example.DrawLayout 
      android:layout_height="match_parent" 
      android:layout_width="match_parent" 
      android:id="@+id/draw"/> 
</LinearLayout> 

回答

3

你不能堅持到Canvas傳遞給onDraw和油漆,只要你喜歡,你可以只畫在畫布上當調用onDraw時。

您應該重新考慮DrawView的設計:有字段存儲關於應繪製的數據的數據,允許方法更改這些字段並根據這些字段在onDraw內部執行實際繪圖。在您的簡單情況下,您可以存儲boolean字段以指示是否應繪製文本(例如isTextVisible),如果字段值爲true,則有一種方法將其設置爲true並在onDraw內繪製該字段。

您可以選擇通過調用invalidate()來強制重繪您的方法,以便更改立即生效。