我有一個存儲在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>