How to add a toast to this view onFinishInflate - java

I am brand new to android and i was wondering if it was possible to add toast onFinishInflate. If this is a stupid question please excuse me.I have created a view like this.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;
import android.widget.Toast;
public class CustomView extends View {
private Rect rectangle;
private Paint paint;
public CustomView(Context context) {
super(context);
int x = 50;
int y = 50;
int sideLength = 200;
// create a rectangle that we'll draw later
rectangle = new Rect(x, y, sideLength, sideLength);
// create the Paint and set its color
paint = new Paint();
paint.setColor(Color.GRAY);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
canvas.drawRect(rectangle, paint);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
Toast.makeText(getApplicationContext(),"onfinishinflate",Toast.LENGTH_SHORT).show();
}
}

Update
View has it's own method called getContext(), so you can use like this
Toast.makeText(getContext(), "onfinishinflate", Toast.LENGTH_SHORT).show();
Reference
private Context context;
public CustomView(Context context) {
super(context);
this.context = context;
// Rest of ur codes
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
Toast.makeText(context, "onfinishinflate", Toast.LENGTH_SHORT).show();
}
set the context in your class using constructor, and use it for Toast purpose

Related

Android Studio Clear DrawView with a Button

I've setup a fragment with a custom View for drawing strokes.
Right now I want to create a button for clearing the strokes, but this is not possible.
I have two classes
extending fragment class
extending the view class
To clear the canvas I've learned to do something like this:
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
The problem is that the Canvas object is stuck inside the onDraw() method.
But I need the canvas object in the button.setOnClickListener the clear the canvas.
How can I do this?
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.app.ssl.R;
import com.app.ssl.databinding.FragmentDrawviewBinding;
public class DrawviewFragment extends Fragment {
private FragmentDrawviewBinding binding;
private View root;
private View drawView;
private Button btnClear;
private Button btnSave;
public View onCreateView(
#NonNull LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceStage) {
root = inflater.inflate(R.layout.fragment_drawview,container,false);
drawView = root.findViewById(R.id.DrawingView);
btnClear = root.findViewById(R.id.btnClean1);
btnSave = root.findViewById(R.id.btnSave);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
System.out.println("CLEAR");
//drawView.setBackgroundColor(Color.WHITE);
// CLEAR CANVAS
//DrawView.canvas.drawColor(Color.WHITE);
//DrawView.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
DrawView.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.MULTIPLY);
//DrawView.onDraw(new Canvas());
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
System.out.println("SAVE");
}
});
return root;
}
}
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawView extends View {
private Paint drawPaint;
private Path path = new Path();
static Canvas canvas;
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
setupPaint();
}
// Setup paint with color and stroke styles
private void setupPaint() {
drawPaint = new Paint();
drawPaint.setColor(Color.BLACK);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(5);
drawPaint.setStyle(Paint.Style.STROKE); // draw with stroke
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
DrawView.canvas = canvas;
canvas.drawPath(path, drawPaint);
}
// Get x and y and append them to the path
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Starts a new line in the path
path.moveTo(pointX, pointY);
break;
case MotionEvent.ACTION_MOVE:
// Draws line between last point and this point
path.lineTo(pointX, pointY);
break;
default:
return false;
}
postInvalidate(); // Indicate view should be redrawn
return true; // Indicate we've co
}
}
I found the solution based on this Tutorial

What's the issue with my onClickListener?

I am trying to write a simple app that displays a coloured circle which fades to black as it gets further from the centre of the screen. However, whenever I click the app, it crashes. When I remove the onClick code the app runs fine. The only error I can find in logcat is:
Fatal signal 11 (SIGSEGV), code 1, fault addr 0x94 in tid 11955 (raphicstutorial)
And I don't know what to do with that.
Code below:
package com.example.a2dgraphicstutorial;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
public class MyView extends View {
private Canvas thisCanvas;
private int colourID;
private Paint fillPaint = new Paint();
public MyView(Context context){
super(context);
colourID = 0;
fillPaint.setStyle(Paint.Style.FILL);
}
public void drawCircle(){
int x = getWidth();
int y = getHeight();
//Drawing the circles
for (int i = 255;i >= 0;i--){
//Determining colour
if (colourID == 0){
fillPaint.setColor(Color.argb(255,255-i,0,0));
}
else if (colourID == 1){
fillPaint.setColor(Color.argb(255,0,255-i,0));
}
else if (colourID == 2){
fillPaint.setColor(Color.argb(255,0,0,255-i));
}
thisCanvas.drawCircle(x/2,y/2,i,fillPaint);
}
//Cycling the colourID so the next circle will be a different colour
colourID = (colourID + 1)%3;
}
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
thisCanvas = canvas;
//Setting the background to be black
fillPaint.setColor(Color.parseColor("#000000"));
thisCanvas.drawPaint(fillPaint);
//Drawing the first circle
drawCircle();
}
}
MyView theScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
theScreen = new MyView(this);
theScreen.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
theScreen.drawCircle();
}
});
setContentView(theScreen);
}
}
Instead of overriding the onCreate()
Override onTouchEvent() and listen to a click:
#Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//the finger is down do something.....
return true;
case MotionEvent.ACTION_UP:
//the finger is up do something.....(this is a click)
//to redraw
invalidate();
return true;
}
return false;
}
By the way:
To trigger the onDraw(), call this after a click:
invalidate();
One upon a time I had a problem similar to this
and the solutions was to replace "this" by "the name of activity".class
// replace this to theScreen = new MyView(this);
theScreen = new MyView(MainActivity.class);
Another solution is to replace this By "getBaseContext()"
// replace this to theScreen = new MyView(this);
theScreen = new MyView(getBaseContext());
this the context returns the current context of the activity, belong to the activity, the activity is destroyed then it will destroy also.
getBaseContext() is the method of ContextWrapper Which is "Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behaviour
without changing the original Context."
That error occurs when you call the Canvas outside of the onDraw method, try this code
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
public class MyView extends View {
private Canvas thisCanvas;
private int colourID;
private Paint fillPaint = new Paint();
public MyView(Context context){
super(context);
colourID = 0;
fillPaint.setStyle(Paint.Style.FILL);
}
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
thisCanvas = canvas;
//Setting the background to be black
fillPaint.setColor(Color.parseColor("#000000"));
thisCanvas.drawPaint(fillPaint);
int x = getWidth();
int y = getHeight();
//Drawing the circles
for (int i = 255;i >= 0;i--){
//Determining colour
if (colourID == 0){
fillPaint.setColor(Color.argb(255,255-i,0,0));
}
else if (colourID == 1){
fillPaint.setColor(Color.argb(255,0,255-i,0));
}
else if (colourID == 2){
fillPaint.setColor(Color.argb(255,0,0,255-i));
}
thisCanvas.drawCircle(x/2,y/2,i,fillPaint);
}
//Cycling the colourID so the next circle will be a different colour
colourID = (colourID + 1)%3;
}
}
MyView theScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
theScreen = new MyView(this);
theScreen.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
theScreen.invalidate();
}
});
setContentView(theScreen);
}
}
I moved the drawCircle method to inside the onDraw and change theScreen from calling drawCircle to call invalidate() instead, I'm not sure it's the result you want but at least that's the issue of the error.

onDraw does not work on ImageView Android

I need to draw a point on ImageView Android.
I use custom subclass of View class and override onDraw method like:
public class DrawPoints extends View {
private float x;
private float y;
private Paint mPaint;
public DrawPoints(Context context, float x, float y) {
super(context);
this.x = x;
this.y = y;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.i("TAG", "onDraw: " + x + "" + y);
mPaint = new Paint();
mPaint.setColor(Color.YELLOW);
canvas.drawCircle(x,y,200,mPaint);
}
}
In my MainActivity I use onTouch event to draw, also do not forget to invalidate(), but it does not draw a point.
public class MainActivity extends AppCompatActivity {
private ImageView mImageView;
private Canvas mCanvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCanvas = new Canvas();
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.image_main);
mImageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float y = motionEvent.getY();
float x = motionEvent.getX();
new DrawPoints(MainActivity.this,x,y).draw(mCanvas);
mImageView.invalidate();
return false;
}
});
}
}
What could it be? I have already read many examples with onDraw on stackoverflow but none help.
You could just create an imageview that draw circle on touch events.
Example:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import java.util.ArrayList;
public class DrawPoints extends android.support.v7.widget.AppCompatImageView {
private static final String TAG = DrawPoints.class.getSimpleName();
private ArrayList<Point> mSavedPoints = new ArrayList<>();
private Point mLastTouchPoint;
private Paint mPaint;
public DrawPoints(Context context) {
super(context);
init();
}
public DrawPoints(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DrawPoints(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.YELLOW);
}
#Override public boolean dispatchTouchEvent(MotionEvent event) {
mLastTouchPoint = new Point((int) event.getX(), (int) event.getY());
postInvalidate();
return super.dispatchTouchEvent(event);
}
#Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mLastTouchPoint != null) {
if (mLastTouchPoint.x > 0 || mLastTouchPoint.y > 0) {
mSavedPoints.add(mLastTouchPoint);
Log.i(TAG, mLastTouchPoint.toString());
}
}
for (Point point : mSavedPoints) {
canvas.drawCircle(point.x, point.y, 200, mPaint);
}
Log.i(TAG, mSavedPoints.toString());
}
}

Why my view does not get my touch event

I have the following code:
package com.teste;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class ball extends View implements View.OnTouchListener {
Bitmap littleBall;
float x, y;
private int mWidth, mHeight;
private GestureDetector mDetector;
public ball(Context context) {
super(context);
}
public ball(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mDetector = new GestureDetector(this.getContext(), new BallListener());
}
#Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
mWidth = View.MeasureSpec.getSize(widthMeasureSpec);
mHeight = View.MeasureSpec.getSize(heightMeasureSpec);
x = mWidth/2;
y = mHeight/2;
setMeasuredDimension(mWidth, mHeight);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
littleBall = BitmapFactory.decodeResource(getResources(), R.drawable.verde);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(littleBall, 200, 200, false);
canvas.drawBitmap(resizedBitmap, (x - (resizedBitmap.getWidth() / 2)), (y - resizedBitmap.getHeight()/2), null);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(getContext(), "teste", Toast.LENGTH_LONG);
return mDetector.onTouchEvent(event);
}
class BallListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_UP) {
x = e.getX();
y = e.getY();
invalidate();
}
return super.onSingleTapUp(e);
}
}
}
In a near future i want make the ball moves to a place when i swipe my finger across the screen. But for the start, my goal is make the LittleBall (created using canvas and bitmap) change its position when i touch at the screen. I am using onTouch and a gestureListener. Searching on the net, i found others ways to get a touch like onTouchListener and even looking and Android Developer Help i did not understand what is the difference between those methods...
Can Someone explain in a easy way when i should use those methods and what im doing wrong to not even show my text?

android drawPoint() not drawing anything

I am an amateur programmer, and have been playing around with android development. I am currently trying my hand at generating a fractal heightmap. In order to test if teh map is generating properly I need to be able to draw the map to the screen. This is where I've been running into trouble.
Here's the code for my MainActivity, DrawMap class (where my onDraw() is), and my CanvasThread() class.
Main Activity:
package com.psstudios.HMG;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View.OnClickListener;
import android.util.Log;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
Button Startgen = null;
Boolean run=true;
private void log(String text) {
Log.d("heightmap",text);
AppendLog app = new AppendLog(text);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Startgen = (Button) findViewById(R.id.startgen);
log("loop");
Startgen.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
log("Starting world generation");
WorldGen world=new WorldGen(200,200);
log("World generation complete, drawing heightmap");
setContentView(new DrawMap(MainActivity.this, world));
log("Went too far");
}
});
run=false;
}
}
DrawMap:
package com.psstudios.HMG;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Bitmap;
import android.graphics.Bitmap.*;
import android.graphics.Paint;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.util.Log;
import android.util.*;
public class DrawMap extends SurfaceView implements SurfaceHolder.Callback
{
int drawtype=1; //variable for which type of map to draw
Bitmap drawbitmap=null;
CanvasThread canvasThread=null;
Boolean run= true;
int Worldx=200;
int Worldy=200;
WorldGen _world=null;
public void log(String text){
Log.d("Heightmap", text);
AppendLog app = new AppendLog(text);
}
public void init(){
log("init();");
canvasThread=new CanvasThread(getHolder(), this);
setFocusable(true);
log("Post-CanvasThread");
}
public DrawMap(Context context){
super(context);
log("DrawMap(Context context)");
getHolder().addCallback(this);
init();
}
public DrawMap(Context context, AttributeSet attrs) {
super(context, attrs);
log("DrawMap(Context context, AttributeSet attrs)");
getHolder().addCallback(this);
init();
}
public DrawMap(Context context,WorldGen world){
super(context);
log("DrawMap(Context context, WorldGen world)");
getHolder().addCallback(this);
_world=world;
init();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,int width, int height){
log("surfaceChanged()");
}
#Override
public void surfaceCreated(SurfaceHolder holder){
log("Surface Created");
canvasThread.setRunning(true);
canvasThread.run();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
log("Surface Destroyed");
Boolean retry = true;
canvasThread.setRunning(false);
while(retry){
try {
canvasThread.join();
retry=false;
} catch (InterruptedException e) {
//we will try again and again
}
}
}
#Override
public void onDraw(Canvas canvas){
log("onDraw()");
Paint paint = new Paint();
Paint paint2 = new Paint();
//canvas.drawColor(Color.BLACK);
paint.setColor(Color.WHITE);
paint.setStrokeWidth(10);
paint2.setColor(Color.BLUE);
for(int x=0; x<Worldx-1; x++){
for(int y=0; y<Worldy-1; y++){
//log(x + " : " + y);
canvas.drawPoint(x+20, y+20, paint);
canvas.drawPoint(x+220, y+220, paint2);
}
}
}
}
CanvasThread:
package com.psstudios.HMG;
import android.graphics.Canvas;
import android.view.*;
import android.util.Log;
public class CanvasThread extends Thread
{
private SurfaceHolder _surfaceHolder;
private DrawMap _drawMap;
private Boolean _run = false;
private void log(String text){
Log.d("HeightmapGen",text);
AppendLog app = new AppendLog(text);
}
public CanvasThread(SurfaceHolder surfaceHolder, DrawMap drawMap){
_surfaceHolder=surfaceHolder;
_drawMap=drawMap;
log("CanvasThread()");
}
public void setRunning(Boolean run){
log("setRunning()");
_run=run;
}
#Override
public void run() {
log("run()");
Canvas c;
while(_run){
c=null;
try{
c=_surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
_drawMap.onDraw(c);
}
} finally {
if(c != null){
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
The program makes it to the onDraw(); function, and runs through the for loop, but nothing is showing up on the screen. I imagine I'm missing something pretty stupid, but I cannot seem to figure out what's wrong.
Thanks in advance for any help you guys can give me.

Categories

Resources