活动自定义视图中的Android引用方法
我有一个自定义视图,它存储在XML布局中。XML布局是“我的活动”的视图。我可以从我的活动中引用XML布局中的自定义视图,就像您对任何Android小部件所做的那样。然后我可以得到onTouch监听器,它工作得很好。我希望能够做的是引用自定义视图中的一个方法,它将使我能够在画布上绘制。我已经通过使用下面的代码打成平局,但没有成功。任何帮助都将不胜感激。PS我的代码做的远不止这些,我刚刚列出了我认为最必要的东西活动自定义视图中的Android引用方法,android,Android,我有一个自定义视图,它存储在XML布局中。XML布局是“我的活动”的视图。我可以从我的活动中引用XML布局中的自定义视图,就像您对任何Android小部件所做的那样。然后我可以得到onTouch监听器,它工作得很好。我希望能够做的是引用自定义视图中的一个方法,它将使我能够在画布上绘制。我已经通过使用下面的代码打成平局,但没有成功。任何帮助都将不胜感激。PS我的代码做的远不止这些,我刚刚列出了我认为最必要的东西 public class DrawView extends View {
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>
您不能抓住传递给
onDraw
的画布
并随时绘制,您只能在调用onDraw
时在画布上绘制
您应该重新考虑DrawView
的设计:让字段存储有关应绘制内容的数据,允许方法更改这些字段,并基于这些字段在onDraw
中进行实际绘制。在您的简单示例中,您可以存储一个布尔
字段来指示是否应该绘制文本(例如isTextVisible
),有一种方法将其设置为true
,并在onDraw
中绘制它(如果字段值为true
)
您可以通过调用invalidate()
,选择使您的方法强制重画,从而使更改立即生效