1

我有一个存储在 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>
4

1 回答 1

3

您不能随时保持Canvas传递给onDraw并绘制,您只能在onDraw被调用时在画布上绘制。

您应该重新考虑以下设计DrawView:让字段存储有关应绘制的数据的数据,允许更改这些字段的方法并根据这些字段在内部进行实际绘图onDraw。在您的简单情况下,您可以存储一个boolean字段以指示是否应绘制文本(例如isTextVisible),如果字段值为 ,则具有将其设置为true并在内部绘制的方法。onDrawtrue

您可以选择通过调用使您的方法强制重绘invalidate(),因此更改会立即生效。

于 2013-08-25T21:16:15.170 回答