如何将画布绘图与包含按钮和布局的android活动布局相结合?

时间:2014-08-14 18:06:41

标签: android android-canvas

我正在尝试使用其活动布局上的按钮构建应用程序,但我希望使用

在同一活动上绘制得分
$canvas.drawText()

我们使用

$setContentView(R.id.activity)

用于设置布局的内容视图,并使用

$SurfaceView sv = new SurfaceView(this);
$setContentView(sv)

用于绘图,但我们如何将两者结合在一起?

1 个答案:

答案 0 :(得分:2)

由于分数只需要偶尔重新绘制,因此您需要的是一个自定义视图,它将扩展View类,该类将在主(UI)线程上运行。如果你是动画,让我们说一个时钟或其他动画需要以固定的时间间隔重绘,或者如果渲染花费太多时间,那么最好将SurfaceView与另一个Thread一起扩展},它可以正确处理动画时间,而不会中断任何其他操作。

让我们看一个自定义视图的基本示例,每次调用公共changeColor()方法时都会更改其颜色:

public class CustomView extends View {

    ...

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Random rand = new Random();
        canvas.drawRGB(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
    }

    public void changeColor() {
       invalidate(); // redraws the view calling onDraw()
    }

}

要正确处理视图大小,您还需要根据需要覆盖onSizeChanged()onMeasure()或其他回调方法。现在您可以在xml布局上使用它了:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/change_color"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Change Color" />
    <org.example.yourpackages.CustomView
        android:id="@+id/custom_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />    
</LinearLayout>

您可以像使用其他任何小部件一样在活动中使用它:

public class CustomViewActivity extends Activity implements OnClickListener {

    private CustomView customView;            
    private Button changeColorBtn;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.custom_view_activity);

            customView = (CustomView)findViewById(R.id.custom_view);
            changeColorBtn = (Button)findViewById(R.id.change_color);
            changeColorBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        customView.changeColor();
    }

}

为了更好地理解其工作原理:

相关问题