我有一个存储在 XML 布局中的自定义视图。XML 布局是我的活动的视图。我可以从我的 Activity 中引用 XML 布局中的自定义视图,就像您对任何 Android Widget 一样。然后我可以得到工作正常的 onTouch 监听器。我想要做的是在我的自定义视图中引用一个方法,这将使我能够在画布上绘图。我已经通过使用以下代码绑定但没有成功。任何帮助将非常感激。PS 我的代码做的远不止这些,我刚刚列出了我认为最需要的。
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);
}
}
主要活动:
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>