Android - Update custom view from asynctask - android

I have a custom view class
public class DrawingView extends View {
//drawing path
private Path drawPath;
//drawing and canvas paint
private Paint drawPaint, canvasPaint;
//initial color
private int paintColor = 0x00660000;
...
public void printPoint(Point p, Boolean b){
if(p != null){
Paint testePaint = new Paint();
testePaint.setColor(0xFF0000FF);
testePaint.setAntiAlias(true);
testePaint.setStrokeWidth(brushSize);
testePaint.setStyle(Paint.Style.STROKE);
testePaint.setStrokeJoin(Paint.Join.ROUND);
testePaint.setStrokeCap(Paint.Cap.ROUND);
if(b){
testePaint.setColor(0xFFFF0000);
}else{
testePaint.setColor(0xFF0000FF);
}
drawCanvas.drawPoint(p.x, p.y, testePaint);
}
}
public void printPath(){
if(paths.size() > 0){
Path testePath = new Path();
Paint testePaint = new Paint();
testePaint.setColor(0xFF00FF00);
testePaint.setAntiAlias(true);
testePaint.setStrokeWidth(brushSize);
testePaint.setStyle(Paint.Style.STROKE);
testePaint.setStrokeJoin(Paint.Join.ROUND);
testePaint.setStrokeCap(Paint.Cap.ROUND);
testePath = paths.remove(0);
drawCanvas.drawPath(testePath, testePaint);
}
}
}
add the view to the layout and load it into MainActivity using
public class MainActivity extends Activity implements OnClickListener {
//TCP COM
private TcpClient mTcpClient;
//
private DrawingView drawView;
private ImageButton currPaint, drawBtn, eraseBtn, newBtn;
private float smallBrush, mediumBrush, largeBrush;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
currPaint = (ImageButton)paintLayout.getChildAt(0);
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
drawView = (DrawingView)findViewById(R.id.drawing);
drawView.setBrushSize(mediumBrush);
....
}
when I click a button I call the following function
public void updateView(Linha l){
Log.d("TCP","updateView()");
if(l.getEscreve() == true){
drawView.printPath();
}
drawView.printPoint(l.getPonto(),l.getEscreve());
}
and it works but when I call it from onProgressUpdate from an asynctask I can only see the draws on the view if I click again on the button.

hmm I don't think you should be updating UI on a different thread. Instead you override onDraw in your custom view, and from your asynctask do postInvalidate to trigger onDraw being called on UI thread.

Add invalidate(); after drawPath and drawPoint resolved the problem :)

Related

android: How to draw on a canvas of a view from another customized class?

I will be very grateful is somebody can help.
I have created a grid of views with a TableLayout in my xml file.
In the corresponding java file, I retrieve the id of all views in an array view.
I have another class which receive in its constructor a reference to an above created view, in order to draw on its canvas.
public class Mosaique extends Activity {
Box [][]box = new Box[NL][NC];
View [][] boxMosaique = new View[NL][NC];
//...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mosaique);
boxMosaique[0][0] = findViewById(R.id.b_00);
boxMosaique[0][1] = findViewById(R.id.b_01);
boxMosaique[0][2] = findViewById(R.id.b_02);
//…
for (int lig=0;lig<NL;lig++)
for(int col=0;col<NC;col++)
box[lig][col] = new Box(boxMosaique[lig][col], bckgrnd_color, lig,col);
}
//...
}
// The constructor of the another class which access the views for drawing
public Box(View aView, int backGroundColor, int lig, int col){
this.aView = aView;
this.lig = lig;
this.col = col;
this.backGroundColor = backGroundColor;
// How to access the canvas of aView for drawing ?
}
I would recommend writing Box class as View.
Box extends View{
float lig;
float col;
Clolr backGroundColor;
...
#Override
protected void onDraw(Canvas canvas) {
//draw here on canvas
...
}
public drawBox(int backGroundColor, int lig, int col){
this.aView = aView;
this.lig = lig;
this.col = col;
this.backGroundColor = backGroundColor;
invalidate()
}
instead of adding constructors, add a method to set box values and call invalidate() once the values are set.

App not drawing

I have my class:
public class CustomDrawableView extends View{
private ShapeDrawable shapeDrawable;
public CustomDrawableView(Context context) {
super(context);
shapeDrawable = new ShapeDrawable(new OvalShape());
shapeDrawable.getPaint().setColor(Color.GREEN);
shapeDrawable.setBounds(20,20,20,20);
}
protected void onDraw(Canvas canvas){
shapeDrawable.draw(canvas);
}
}
Then in the main activity I have this code in the oncreate function:
private CustomDrawableView customDrawableView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
customDrawableView = new CustomDrawableView(this);
setContentView(customDrawableView);
}
For some reason, it doesn't draw though. I have my CustomDrawableView class which I have created an instance of in the oncreate method in mainactiviy. I have set the content view to the instance of my class too.
Also, is this a good way to create graphics for a game I want to make. Thanks
Check this call:
shapeDrawable.setBounds(20,20,20,20);
the parameters are left, top, right, bottom, so it effectively sets the size of the drawable to 0.

how to call a user defined method in a custom view from an activity

i want to call the start method defined in Gameview class from the NewGame activity.basically i want to add onclicklistener and want to perform task specified inthe start() method whenever the button is clicked
activity:
public class NewGame extends Activity implements OnClickListener {
GameView gameview;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//gameview=new GameView(this);
setContentView(R.layout.activity_new_game);
View startbutton=findViewById(R.id.start_button);
startbutton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_button:
gameview.start(this);
}
}
view:
public class GameView extends View {
Path circle;
Paint cPaint;
Paint tPaint;
String z;
GameView a;
int i=65,strt,arc,leftx,topy,rightx,bottomy,maxx,maxy,minx,miny;
boolean flag1,flag2,flag3;
double n1,n2;
int n,n3=180,n4,n5=90;
float f1=180,f2=90;
int width;
int height;
Random r=new Random();
RectF oval;
public GameView(Context context,AttributeSet attrs ) {
super(context,attrs);
leftx=0;
topy=60;
rightx=150;
bottomy=120;
z= String.valueOf(Character.toChars(i));
cPaint = new Paint();
cPaint.setColor(Color.RED);
strt=45;
arc=315;
n1=Math.random()*600;
Log.d("random",z);
this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// cPaint.setStrokeWidth(2);
tPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
tPaint.setStyle(Paint.Style.FILL_AND_STROKE);
tPaint.setColor(Color.BLACK);
float scale = getResources().getDisplayMetrics().scaledDensity;
tPaint.setTextSize(20 * scale);
}
public void start(Context context)
{
if (flag2==false)
new DrawThread(this);
}
Your gameView object is currently null. If you have it in your XML layout file, you should instantiate it in onCreate with a line like this:
gameView = (GameView) findViewById(R.id.gameView);//where gameView is the id specified in your layout file (R.layout.main, or something)
If it is not in your layout file, you need to instantiate it and add it to your layout:
gameView = new GameView(this);
gameView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
ViewGroup content = (ViewGroup) findViewById(android.R.id.content).getRootView();
content.addView(gameView);
now you will not get null pointer exceptions, and your gameview will fill the screen.

Android, typeface not copied into new paint

In the following code:
Paint tPaint = new Paint(aPaint);
tPaint.setTypeface(typeFace);
aPaint = new Paint(tPaint);
typeFace is observed set into tPaint but, typeFace does not get copied into aPaint.
Ok that´s how my code look like. See if you can find anything.
MainView.java
public class MainView extends View {
Context context;
public MainView(Context context) {
super(context);
this.context = context;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint apaint = new Paint();
apaint.setTextSize(100);
apaint.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/sketchblock.ttf"));
canvas.drawText("Dusean", canvas.getWidth()/2, canvas.getHeight()/2, apaint);
Paint tpaint = new Paint(apaint);
canvas.drawText("Dusean", canvas.getWidth()/3, canvas.getHeight()/3, tpaint);
}
}
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MainView(this));
}
}
and font in the Assets folder assets/fonts/font.ttf
This is not exactly an answer but a work around.
I replaced the: aPaint = new Paint(tPaint); with: aPaint = newPaint(tPaint); and created the method:
public Paint newPaint(Paint fromPaint){
Typeface tf = fromPaint.getTypeface();
Paint rPaint = new Paint(fromPaint);
rPaint.setTypeface(tf);
return rPaint;
}
This works.

How to create a view on an activity

So I have this class which extends an activity. But I want to draw something on the screen, so I need to make a canvas. However I can't extends View, because it's an activity allready. What should I do?
My activity has the onClick method which I use to do some stuff, but what I wanna do is draw a simple image when I call the onClick method as well.
Thanks.
public class Stuff extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
(...)
}
#Override
public void onClick(View arg0) {
(...)
}
STEP 1: create a class by extends View as:
public class DrawView extends View {
public float currentX=40;
public float currentY=50;
public DrawView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint=new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(currentX, currentY, 25, paint);
}
}
STEP 2: In Your Stuff Activity :
public class Stuff extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout root=(LinearLayout) findViewById(R.id.root);
(...)
}
#Override
public void onClick(View arg0) {
//DRAW YOUR VIEW ON BUTTON CLICK
final DrawView drawView=new DrawView(this);
drawView.setMinimumWidth(300);
drawView.setMinimumHeight(500);
drawView.currentX=200;
drawView.currentY=200;
drawView.invalidate();
root.addView(drawView);
(...)
}
STEP 3: Your Activity main.xml as :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#99FFCC"
android:id="#+id/root">
</LinearLayout>
and finally try to search on google before asking question here.thanks
You can declare an inner class within ur activity for ex refer this code:
public class GraphicsTest extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GraphicsTestView(this));
}
private static class GraphicsTestView extends View
{
private ShapeDrawable mDrawable =
new ShapeDrawable();
/* Drawable's are objects which can be drawn on a Canvas
ShapeDrawable is used to draw primitive shapes such as:
ArcShape, OvalShape, PathShape, RectShape, RoundRectShape
A Canvas is the object provided by Android on which
a view tries to draw itself. In addition to ShapeDrawable,
there are other subclasses of Drawable like PictureDrawable,
RotateDrawable, ScaleDrawable, ClipDrawable,GradientDrawable, etc
Some of these we will see when we consider the XML approach to
graphics
*/
public GraphicsTestView (Context context)
{
super(context);
setFocusable(true);
this.mDrawable.getPaint().setColor(0xFFFF0000);
//argb where a is alpha (transparency)
}
#Override
protected void onDraw(Canvas canvas)
/* the onDraw method is where a view draws itself
this is our first time overriding it.
*/
{
int x = 10;
int y = 10;
int width = 300;
int height = 50;
this.mDrawable.setBounds(x, y, x + width, y + height);
this.mDrawable.draw(canvas);
ArcShape arc = new ArcShape(45,90); //start angle, sweep angle
ShapeDrawable test = new ShapeDrawable(arc);
Paint p = test.getPaint();
p.setColor(0xFF00FFFF);
p.setStyle(Paint.Style.STROKE);
test.setBounds(10, 70, 310, 370);
//Top-Left, Bottom Right of rectangle to draw into
test.draw(canvas);
}
}
}
Are you saying you want to get the layout view in your XML file? You can draw the views in it, get your code to call it and view it, and then set the images to respond when clicked.
In your onCreate method, after super.onCreate(savedInstanceState); add this setContentView(R.id.layoutname)
For example
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
As for the onClickListener, you can set the views to implement it like this since you already implement it in the Activity.
// set this after "setContentView(R.layout.main);"
b1 = (Button)findViewById(R.id.main);
b1.setOnClickListener(this);

Categories

Resources