gpt4 book ai didi

android - 如何将 Canvas 绘图与包含按钮和布局的 android Activity 布局相结合?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:04:12 27 4
gpt4 key购买 nike

我正在尝试构建一个在其 Activity 布局上带有按钮的应用程序,但我希望使用以下方法在同一 Activity 上绘制分数

$canvas.drawText()

我们用

$setContentView(R.id.activity)

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

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

用于绘图,但我们如何将两者结合在同一个 Activity 中?

最佳答案

由于乐谱只是偶尔需要重新绘制,看来您需要的是一个扩展 View 类的自定义 View ,它将在主 (UI) 线程上运行。如果您正在制作动画,比方说需要以固定时间间隔重新绘制的时钟或其他一些动画,或者如果渲染花费太多时间,那么最好将 SurfaceView 与另一个 一起扩展code>Thread,它将正确处理动画时间,而不会中断任何其他操作。

让我们看一个自定义 View 的基本示例,每次调用公共(public) 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()
}

}

要正确处理 View 大小,您还需要根据需要覆盖 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>

您可以像使用其他小部件一样在您的 Activity 中使用它:

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

}

为了更好地理解它是如何工作的:

关于android - 如何将 Canvas 绘图与包含按钮和布局的 android Activity 布局相结合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25314707/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com