Calling a class from a class with parameters (Cannot resolve symbol) - java

I'm pretty new to programming so it might be that I've gotten the whole idea wrong here but..
I have two classes, other is the main class (Main) and the second (DrawingLines) is just plain one. I'm trying to call an onDraw method from the DrawingLines in my main class.
I did a bit of research but all i found was to use
DrawingLines draw = new DrawingLines ();
draw.onDraw
And I think this is how it's supposed to be but I just cant figure out what parametres I should use. You can see the parametres I've been trying to use in the example below, but AndroidStudio just gives "Cannot resolve symbol".
Main class:
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout parent = (LinearLayout) findViewById(R.id.parent);
final TextView text = (TextView) findViewById(R.id.text);
parent.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent ev) {
text.setText("Touch at " + (int)ev.getX() + ", " + (int)ev.getY());
return true;
}
});
}
DrawingLines draw = new DrawingLines(Context context);
draw.onDraw(canvas);
}
DrawingLines class:
class DrawingLines extends View {
public DrawingLines(Context context) {
super(context);
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Rect pallo = new Rect();
pallo.set(0, 0, canvas.getWidth(), canvas.getHeight() / 2);
Paint blue = new Paint();
blue.setColor(Color.BLUE);
blue.setStyle(Paint.Style.FILL);
canvas.drawRect(pallo, blue);
}
}

Your code is not in a method:
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout parent = (LinearLayout) findViewById(R.id.parent);
final TextView text = (TextView) findViewById(R.id.text);
parent.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent ev) {
text.setText("Touch at " + (int)ev.getX() + ", " + (int)ev.getY());
return true;
}
});
DrawingLines draw = new DrawingLines(this.getApplicationContext());
draw.onDraw(canvas);
}//onCreate
}//class main

First of all, if you want to draw something you don't have to force it programmatically. DrawingLines draw = new DrawingLines(Context context);
draw.onDraw(canvas)
Put your view DrawingLines inside layout R.layout.activity_main and create variable use findViewById.
Then you can perform drawingLines.invalidate() on that view, so the View will be redrawn (method void onDraw(Canvas canvas) will be called).

I created a simple project that can draw by finger (I put all staff that performs draw in custom view)
DrawView:
public class DrawView extends View {
private final static String LOG = "CUSTOM_LOG";
private Paint paint;
private Path path = new Path();
public DrawView(Context context) {
this(context, null);
}
public DrawView(Context context, #Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
Log.d(LOG, "init");
setOnTouchListener(onTouchListener);
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStrokeWidth(15);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d(LOG, "onDraw");
canvas.drawPath(path, paint);
}
private OnTouchListener onTouchListener = new OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float x = motionEvent.getX();
float y = motionEvent.getY();
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d(LOG, "ACTION_DOWN");
path.moveTo(x, y);
break;
case MotionEvent.ACTION_MOVE:
Log.d(LOG, "ACTION_MOVE");
path.lineTo(x, y);
break;
case MotionEvent.ACTION_UP:
Log.d(LOG, "ACTION_UP");
path.reset();
break;
}
invalidate();
return true;
}
};
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.gitlab.onreg01.simpledrawexample.DrawView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"/>
</FrameLayout>
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
project repository

Related

Is there a way to draw on screen programmatically in android studio using java

I want to create an android app that draw on current layout of app without setting any other Contentview. This is the code that I have did but in this code it is creating an other view and then allow to draw but not on current layout.
**Canva Class:**
public CanvaClass(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
path = new Path();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5f);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path,paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = event.getX();
float yPosition = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
path.moveTo(xPosition,yPosition);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(xPosition,yPosition);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
invalidate();
return true;
}
}
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CanvaClass canvaClass = new CanvaClass(getApplicationContext(),null);
setContentView(canvaClass);
}
});
}
}

Empty screen is also saved

Paint app where you can delete and save. Basically i don't want to save empty screen. Bitmap is converted to base64. But right now it shows base64 value in logs even when it's empty. How to do it?
Troubleshooting: i have tired checking if bitmap is empty, also tried if bytearray is empty. Nothing worked. Any guidance??
public class PaintView extends View {
Canvas mCanvas; // 1
Bitmap mBitmap ,emptyBitmap ; //2 , to hold the pixels
Path mPath; // 3, encapsulates outline representing (multiple contuer) straight lines ,curves. can be drawn with canvas.drawpath(path,paint)
Paint mPaint; //4
private float mX, mY;
private static final float TOUCH_TOLERANCE = 5;
Context context;
public PaintView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
this.context = context;
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true); //smoothes the edges of what is being drawn
mPaint.setStyle(Paint.Style.STROKE); // style is specifies as stroke. Options: Fill,fill and stroke
mPaint.setColor(Color.BLACK);
mPaint.setStrokeJoin(Paint.Join.ROUND); //more options for round
mPaint.setStrokeWidth(4f);
}
#Override //called when the size of view is changed
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100 , stream);
byte[] byteFormat = stream.toByteArray();
String imgString = Base64.encodeToString(byteFormat, Base64.DEFAULT);
Log.d("check", "saved successfully");
return imgString;
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button button_clear_canvas;
private PaintView canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
canvas = findViewById(R.id.canvasview);
button_clear_canvas = findViewById(R.id.button_clear_canvas);
button_clear_canvas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveDialog();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_erase,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.erase:
CreateDialog();
}
return true;
}
public void SaveDialog(){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
mBuilder.setMessage("Are you sure you want to save?");
mBuilder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
if(canvas.mBitmap != null){
canvas.getEncoded64ImageStringFromBitmap(canvas.mBitmap);
}
} catch (Exception e) {
Log.v("log_tag", e.toString());
}
}
});
mBuilder.setNegativeButton("NO",null);
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();
}
public void CreateDialog(){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
mBuilder.setMessage("Are you sure ?");
mBuilder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
canvas.OnClearCanvas();
}
});
mBuilder.setNegativeButton("NO",null);
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();
}

How to use touch screen and keyboard (external keyboard) at the same on android 5.1 app?

In my android app when i add touch screeen methods and i want to read at the same the keyboard with onkey method, i just lost one of them.
My question is : how can i use them both at the same time.
here is my main class :
public class SingleTouchActivity extends AppCompatActivity {
EditText edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_single_touch);
setContentView(new SingleTouchEventView(this, null));
edit= (EditText) findViewById(R.id.editText);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_0){
edit.setText("here we go");
}
return super.onKeyDown(keyCode,event);
}
}
And i have a class for touch screen which i test with draw method:
public class SingleTouchEventView extends View {
private Paint paint = new Paint();
private Path path = new Path();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setFocusable(true);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
}
Does your device support multi-touch?
If yes, try this: (I hope this works)
public class SingleTouchActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_single_touch);
setContentView(new SingleTouchEventView(this, null));
try {
ViewGroup vx = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
EditText et = new EditText(this);
et.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
vx.addView(et);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I have found a solution which is more simple for app. Hope it will helps someone.
`public class MainActivity extends AppCompatActivity {
View myView;
public boolean tmpflag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView= findViewById(R.id.Rec);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int action = ev.getAction();
if (action == MotionEvent.ACTION_DOWN) {
if (tmpflag) {
myView.setBackgroundColor(Color.RED);
tmpflag = false;
} else {
myView.setBackgroundColor(Color.BLUE);
tmpflag = true;
}
return true;
}
return super.dispatchTouchEvent(ev);
}
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keycode= event.getKeyCode();
if (action == KeyEvent.ACTION_DOWN) {
if (keycode ==KeyEvent.KEYCODE_ENTER){
if (tmpflag) {
myView.setBackgroundColor(Color.RED);
tmpflag = false;
} else {
myView.setBackgroundColor(Color.BLUE);
tmpflag = true;
} }
return true;
}
return super.dispatchKeyEvent(event);
}
}
`

Android drawing

I am following a tutorial, and have the following code, but I want to modify it a little bit, so I want when its clicked inside the circle it must be filled with another collor, how I can do it, as I am just learning this concept I dont have any idea of how it can be done :/
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
public class MyView extends View {
public MyView(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
int radius;
radius = 100;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x / 2, y / 2, radius, paint);
}
}
}
you have to add a touch listener on your view
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View myView = new MyView(this);
setContentView(myView);
myView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
//if(x==... your code here
invalidate(); //this repaints the view
return false;
}
});
}
}

How do I change the color/thickness of my paint on a canvas in Android?

I'm not able to change the color or thickness of my paint when I click an imageButton, even though I programmed it too. I know I'm doing something wrong and I think I know why but I can't fix it. I feel like I'm not calling the right paintbrush. Here's my Java Class code:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class CanvasView extends View
{
private Paint paint = new Paint();
private Path path = new Path();
private Canvas canvas = new Canvas();
private Paint canvasPaint = new Paint();
private Bitmap canvasBitmap;
public CanvasView(Context context, AttributeSet attrs)
{
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(5);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas = new Canvas(canvasBitmap);
}
#Override
protected void onDraw(Canvas drawCanvas)
{
drawCanvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
drawCanvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent e)
{
// get the coords of the touch event
float eventX = e.getX();
float eventY = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
// set a new starting point
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
// connect the points
path.lineTo(eventX, eventY);
break;
default:
return false;
}
//makes you view repaint and call ondraw
invalidate();
return true;
}
public void clearCanvas()
{
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
}
Here's my MainActivity code:
public class MainActivity extends Activity {
private CanvasView canvasView;
private Paint paint;
private int orange;
private int purple;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
canvasView = (CanvasView) findViewById(R.id.canvasView);
paint = new Paint();
orange = Color.rgb(255, 245, 238);
purple = Color.rgb(128, 0, 128);
// REGULAR BUTTONS: save, about, reset
Button saveB = (Button) findViewById(R.id.saveButton);
Button aboutB = (Button) findViewById(R.id.aboutButton);
Button resetB = (Button) findViewById(R.id.resetButton);
// IMAGE BUTTONS: red, blue, green, yellow, black, purple, orange, erase, brush thickness plus, brush thickness minus
ImageButton redIb = (ImageButton) findViewById(R.id.redButton);
ImageButton blueIb = (ImageButton) findViewById(R.id.blueButton);
ImageButton greenIb = (ImageButton) findViewById(R.id.greenButton);
ImageButton yellowIb = (ImageButton) findViewById(R.id.yellowButton);
ImageButton blackIb = (ImageButton) findViewById(R.id.blackButton);
ImageButton purpleIb = (ImageButton) findViewById(R.id.purpleButton);
ImageButton orangeIb = (ImageButton) findViewById(R.id.orangeButton);
ImageButton eraseIb = (ImageButton) findViewById(R.id.eraseButton);
ImageButton plusIb = (ImageButton) findViewById(R.id.plusButton);
ImageButton minusIb = (ImageButton) findViewById(R.id.minusButton);
minusIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setStrokeWidth(-5);
}
});
plusIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setStrokeWidth(5);
}
});
eraseIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.TRANSPARENT);
}
});
orangeIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(orange);
}
});
purpleIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(purple);
}
});
blackIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.BLACK);
}
});
yellowIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.YELLOW);
}
});
greenIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.GREEN);
}
});
blueIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.BLUE);
}
});
redIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.RED);
}
});
saveB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
aboutB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AboutActivity.class);
startActivity(intent);
}
});
resetB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasView.clearCanvas();
// canvasView.clearCanvas2();
}
});
}
You are setting your values on a entire different Paint which has no connection to your CanvasView. You would have to change the Paint of your CanvasView and call invalidate on it to make any changes.
Implement something like this in your CanvasView to change the stroke width:
public void setStrokeWidth(int strokeWidth) {
paint.setStrokeWidth(strokeWidth);
invalidate();
}
and call it in your onClick() with canvasView.setStrokeWidth(5);
Same goes for Color:
public void setColor(int color) {
paint.setColor(color);
invalidate();
}
and call it in your onClick() with canvasView.setColor(Color.BLUE);
If you want to implement in Kotlin;
paint.strokeWidth = 3.0f
You have created a Paint object in your activity (let's say paint1) and you have another Paint object in your canvas class (let's say paint2). You're performing the drawing operation using paint2 but in your activity, you're not updating the paint2 instead you're changing the paint1 that is created within the activity. So your changes upon button clicks are not shown.
You need to pass the paint1 object from activity to canvas in order to make changes and also call the invalidate() to redraw with updated paint. See the code below:
public void updateCanvasPaint(Paint paint){
this.paint = paint;
invalidate();
}
Call this in your onClick methods after making changes to paint. Like this:
blueIb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.BLUE);
canvasView.updateCanvasPaint(paint);
}
});

Categories

Resources