Android:单击按钮时的Canvas.drawText

时间:2010-09-10 01:35:53

标签: android button canvas drawtext

按钮点击时如何drawText?当按钮点击时,我如何setContentView(R.layout.main)看到按钮并绘制文本?我无法做到,下面是我绘制文字的代码。

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     drawView = new DrawView(this); 
     setContentView(drawView); 
}
public DrawView(Context context) { 
     super(context); 
     textpaint.setColor(Color.WHITE);
}
public void onDraw(Canvas canvas) {
     canvas.drawText("Testing", 20, 55, textpaint);
}

1 个答案:

答案 0 :(得分:0)

DrawView的继承是什么? 为什么不使用简单的xml布局放置TextView并在setVisible

中使用OnClickListener

示例代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_view);
    Button myButton = (Button) findViewById(R.id.my_button);
    final MySurfaceView surfaceView = (MySurfaceView) findViewById(R.id.mysurface);
    myButton.setOnClickListener(new OnClickListener() {
        @Override
        public boolean onClick(View v) {
            // here you should change the position and the text you want to write
            // like surfaceView.setCoordinates(x, y);
            // and surfaceView.setTextToDraw("myText");
            return true;
        }
    });
}

当然,您需要创建自己的SurfaceView。如何做到这一点:http://www.droidnova.com/playing-with-graphics-in-android-part-ii,160.html

的xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <org.mypackage.MySurfaceView android:id="@+id/mysurface"
        android:layout_width="300dp"
        android:layout_height="300dp" />
    <Button android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Push it real good!" />
</LinearLayout>