Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redraw canvas in a view from activity

I have a class that extends View and have the onDraw method implemented in my xml file I have a FrameLayout with my view and a RelativeLayout with a button

<?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>

in my Activity class I want to implement when I click the button redraw the canvas in MyView class

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

How Can I do that?

like image 658
jos11 Avatar asked May 08 '13 19:05

jos11


People also ask

What is onDraw method?

The parameter to onDraw() is a Canvas object that the view can use to draw itself. The Canvas class defines methods for drawing text, lines, bitmaps, and many other graphics primitives. You can use these methods in onDraw() to create your custom user interface (UI).

What is Canvas in android?

What is a Canvas? Canvas is a class in Android that performs 2D drawing of different objects onto the screen. The saying “a blank canvas” is very similar to what a Canvas object is on Android. It is basically, an empty space to draw onto.


1 Answers

use invalidate().

First change your xml slightly to add an id:

<canvas.pruebas.MyView   android:id="@+id/mycanvasview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

then in code,

   ...
   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();
        }
    });
like image 181
petey Avatar answered Sep 30 '22 22:09

petey