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

use*_*013 5 android android-canvas

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

$canvas.drawText()
Run Code Online (Sandbox Code Playgroud)

我们用

$setContentView(R.id.activity)
Run Code Online (Sandbox Code Playgroud)

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

$SurfaceView sv = new SurfaceView(this);
$setContentView(sv)
Run Code Online (Sandbox Code Playgroud)

进行绘制,但是如何将两者合并到同一活动中呢?

ILo*_*cho 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()
    }

}
Run Code Online (Sandbox Code Playgroud)

要正确处理视图大小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>
Run Code Online (Sandbox Code Playgroud)

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

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

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