我有一个扩展 View 的类并实现了 onDraw 方法 在我的 xml 文件中,我有一个带有 View 的 FrameLayout 和一个带有按钮的 RelativeLayout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<canvas.pruebas.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/btn"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="hello"
android:textSize="15sp"
/>
</RelativeLayout>
</FrameLayout>
在我的 Activity 类中,当我单击按钮时,我想在 MyView 类中重绘 Canvas
public class CanvasActivity extends Activity {
Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//redraw canvas
}
});
}
}
我该怎么做?
最佳答案
使用invalidate() .
首先稍微更改您的 xml 以添加一个 id:
<canvas.pruebas.MyView android:id="@+id/mycanvasview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
然后在代码中,
...
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// get your view
canvas.pruebas.MyView myCanvas = (canvas.pruebas.MyView) findViewById(R.id.mycanvasview);
//redraw canvas
myCanvas.invalidate();
}
});
关于android - 如何在 Activity View 中重绘 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16449039/