I want to write a program which creates a button, whenever I'm touching the screen, the button should be created on the place where the screen was touched.
I wrote a program which creates circles, whenever and where the screen is touched, can anybody explain me how to make buttons instead of circles?
Thx.
Main Activity
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View.OnTouchListener;
public class SingleTouchActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SingleTouchEventView(this, null));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.single_touch, menu);
return true;
}
}
Touch Activity
import java.util.ArrayList; //not all imports are necessary
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.view.View.OnClickListener;
public class SingleTouchEventView extends RelativeLayout {
private Paint paint = new Paint();
List<Point> points = new ArrayList<Point>();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE: // a pointer was moved
case MotionEvent.ACTION_UP:
Point p = new Point();
p.x = (int)event.getX();
p.y = (int)event.getY();
points.add(p);
Button button = new Button(getContext());
int buttonHeight = 50;
int buttonWidth = 50;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);
params.leftMargin = p.x;
params.topMargin = p.y;
addView(button, params);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
}
});
case MotionEvent.ACTION_CANCEL: {
break;
}
}
invalidate();
return true;
}
// Do something
}
First make your class extends a ViewGroup like RelativeLayout and FrameLayout in your case.
Then, on the touch event, create a Button (or a ImageView and setOnClickListener()), adjust the position of the button with margins on the view LayoutParams and add the button to the layout via addView().
Edit: The button creation will be like this on onTouchEvent():
Point p = new Point();
p.x = (int)event.getX();
p.y = (int)event.getY();
Button button = new Button(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);
params.leftMargin = p.x;
params.topMargin = p.y;
addView(button, params);
Also change this to be inside ACTION_UP to prevent creating multiple buttons on long pressing.
This is not possible. You can draw a circle because that is a graphic. If you were to make button appear then you would need to add it to XML. I assume you are making a game that requires elements to randomly appear. I suggest if this is the case to use and engine a spawn random circles and when touched do what you need. Hope this helps
Related
In a little Project of mine I try to set a Point to another Point in OnTouchEvent(). Both points are created in the Constructor like this:
package com.example.samuel.truespeedgame;
import android.content.Context;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private SurfaceViewThread surfaceViewThread;
public Point clickPoint, playerPoint, startPoint;
GamePanel(Context context) {
super(context);
maxSpeed = 20;
playerPoint = new Point(200,200); //very normal instanciating of Points i guess
startPoint = new Point(200,200);
clickPoint = new Point(200,200);
}
My OnTouchEvent() looks like this:
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
// Player has touched the screen
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
if(clickPoint != null)
clickPoint.set((int)motionEvent.getX(),(int)motionEvent.getY());
else if(clickPoint == null) clickPoint = new Point((int)motionEvent.getX(),(int)motionEvent.getY());
startPoint = playerPoint; //Here gets the error thrown
break;
case MotionEvent.ACTION_UP:
}
return true;
}
It was a NullPointerException before I rebuild the Project. Now the playerPoint.x and .y is always 0.
If you don't instantiate GamePanel your playerPoint will be null.
I am trying to implement face detection using Google Mobile Vision in an Android app. In the app, I have an Imageview and a button with text, "Process".
When the button is clicked, the code connects with Google's Vision API and detects the face. After detecting the face, I am trying to draw a rectangle around the face. For that purpose I am using "Canvas" available in Android.
The error (not exactly) is I am unable to see the rectangle around the face. Here is the code in my MainActivity.java file:
package com.startertutorials.googlefacedetect;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import com.google.android.gms.vision.face.Landmark;
public class MainActivity extends Activity {
ImageView imageView;
Button btnProcess;
Bitmap myBitmap;
Canvas canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView);
btnProcess = (Button)findViewById(R.id.btnProcess);
myBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.me);
//imageView.setImageBitmap(myBitmap);
Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), myBitmap.getConfig());
canvas = new Canvas(tempBitmap);
btnProcess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FaceDetector faceDetector = new FaceDetector.Builder(getApplicationContext())
.setTrackingEnabled(false)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.FAST_MODE)
.build();
if (!faceDetector.isOperational()) {
Toast.makeText(MainActivity.this, "Face Detector Setup Failed!", Toast.LENGTH_SHORT).show();
return;
}
Frame frame = new Frame.Builder().setBitmap(myBitmap).build();
SparseArray<Face> sparseArray = faceDetector.detect(frame);
for (int i = 0; i < sparseArray.size(); i++) {
Face face = sparseArray.valueAt(i);
detectLandmarks(face);
}
}
});
}
private void detectLandmarks(Face face) {
float height = face.getHeight();
float width = face.getWidth();
PointF p = face.getPosition();
float cx = p.x;
float cy = p.y;
drawOnImageView(cx, cy, height, width);
/*
for(Landmark landmark:face.getLandmarks())
{
int cx = (int)landmark.getPosition().x;
int cy = (int)landmark.getPosition().y;
drawOnImageView(landmark.getType(),cx,cy);
}
*/
}
private void drawOnImageView(float cx, float cy, float height, float width) {
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(2);
canvas.drawBitmap(myBitmap, 0, 0, null);
canvas.drawRect(0, 0, 200, 200, myPaint);
imageView.setImageBitmap(myBitmap);
Log.d("Success", "Face detected successfully");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The output after I click the "Process" button in the app is as follows:
In the logcat of Android studio, I can see the message "Face detected successfully". So, I am assuming that all my code is running. But I am unable to see the rectangle.
Please help me with displaying a rectangle first. Later I will adjust it to display around the face.
You have to extend the Detector class:
https://developers.google.com/android/reference/com/google/android/gms/vision/Detector
Defining your RectangleDetector class. The code to detect rectangles would be implemented by overriding the detect() method. You'd need to implement this yourself, since there isn't already code for detecting rectangles in mobile vision.
When you have this, you'd be able to use it with CameraSource and other parts of the mobile vision API.
i completed the drawing text on ImageView and i saved the final image in sd card. My problem is, when i am touching the screen to draw the text, my image in the ImageView is disappearing.
Code
import java.io.File;
import java.io.FileOutputStream;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class DrawTextOnImgActivity extends Activity {
private Button btn_save, btn_resume;
private ImageView iv_canvas;
private Bitmap baseBitmap;
private Canvas canvas;
private Paint paint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_text_on_img);
// The initialization of a brush, brush width is 5, color is red
paint = new Paint();
paint.setStrokeWidth(5);
paint.setColor(Color.RED);
iv_canvas = (ImageView) findViewById(R.id.imageView1);
btn_save = (Button) findViewById(R.id.btn_save);
btn_resume = (Button) findViewById(R.id.btn_resume);
btn_save.setOnClickListener(click);
btn_resume.setOnClickListener(click);
iv_canvas.setOnTouchListener(touch);
}
private View.OnTouchListener touch = new OnTouchListener() {
// Coordinate definition finger touch
float startX;
float startY;
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
// Press the user action
case MotionEvent.ACTION_DOWN:
// The first drawing initializes the memory image, specify the background is white
if (baseBitmap == null) {
baseBitmap = Bitmap.createBitmap(iv_canvas.getWidth(),
iv_canvas.getHeight(), Bitmap.Config.ARGB_8888);
canvas = new Canvas(baseBitmap);
canvas.drawColor(Color.WHITE);
}
// Recording began to touch point coordinate
startX = event.getX();
startY = event.getY();
break;
// The user's finger on the screen of mobile action
case MotionEvent.ACTION_MOVE:
// Record the coordinates of the mobile point
float stopX = event.getX();
float stopY = event.getY();
//According to the coordinates of the two points, drawing lines
canvas.drawLine(startX, startY, stopX, stopY, paint);
// Update start point
startX = event.getX();
startY = event.getY();
// The pictures to the ImageView
iv_canvas.setImageBitmap(baseBitmap);
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
return true;
}
};
private View.OnClickListener click = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_save:
saveBitmap();
break;
case R.id.btn_resume:
resumeCanvas();
break;
default:
break;
}
}
};
/**
* Save the image to the SD card.
*/
protected void saveBitmap() {
try {
// Save the image to the SD card.
File folder = new File(Environment.getExternalStorageDirectory() + "/DrawTextOnImg");
if (!folder.exists()) {
folder.mkdir();
}
File file = new File(Environment.getExternalStorageDirectory()+"/DrawTextOnImg/tempImg.png");
FileOutputStream stream = new FileOutputStream(file);
baseBitmap.compress(CompressFormat.PNG, 100, stream);
Toast.makeText(DrawTextOnImgActivity.this, "Save the picture of success", Toast.LENGTH_SHORT).show();
// Android equipment Gallery application will only at boot time scanning system folder
// The simulation of a media loading broadcast, for the preservation of images can be viewed in Gallery
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
sendBroadcast(intent);
} catch (Exception e) {
Toast.makeText(DrawTextOnImgActivity.this, "Save failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
/**
* Clear the drawing board
*/
protected void resumeCanvas() {
// Manually clear the drawing board, to create a drawing board
if (baseBitmap != null) {
baseBitmap = Bitmap.createBitmap(iv_canvas.getWidth(), iv_canvas.getHeight(), Bitmap.Config.ARGB_8888);
canvas = new Canvas(baseBitmap);
canvas.drawColor(Color.WHITE);
iv_canvas.setImageBitmap(baseBitmap);
Toast.makeText(DrawTextOnImgActivity.this, "Clear the drawing board, can be re started drawing", Toast.LENGTH_SHORT).show();
}
}
}
Manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<protected-broadcast android:name="android.intent.action.MEDIA_MOUNTED" />
By using this code i am writing the text on ImageView but image in the ImageView is disappearing. So, please help me to write the text on image of ImageView
I achieved it by fallowing this code
DrawTextOnImgActivity
import java.io.File;
import java.io.FileOutputStream;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
public class DrawTextOnImgActivity extends Activity {
ImageView ivDrawImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_text_on_img);
ivDrawImg = (ImageView) findViewById(R.id.iv_draw);
Button btnSave = (Button) findViewById(R.id.btn_save);
Button btnResume = (Button) findViewById(R.id.btn_resume);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
saveImg();
}
});
btnResume.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void saveImg(){
Bitmap image = Bitmap.createBitmap(ivDrawImg.getWidth(), ivDrawImg.getHeight(), Bitmap.Config.RGB_565);
ivDrawImg.draw(new Canvas(image));
String uri = Images.Media.insertImage(getContentResolver(), image, "title", null);
Log.e("uri", uri);
try {
// Save the image to the SD card.
File folder = new File(Environment.getExternalStorageDirectory() + "/DrawTextOnImg");
if (!folder.exists()) {
folder.mkdir();
//folder.mkdirs(); //For creating multiple directories
}
File file = new File(Environment.getExternalStorageDirectory()+"/DrawTextOnImg/tempImg.png");
FileOutputStream stream = new FileOutputStream(file);
image.compress(CompressFormat.PNG, 100, stream);
Toast.makeText(DrawTextOnImgActivity.this, "Picture saved", Toast.LENGTH_SHORT).show();
// Android equipment Gallery application will only at boot time scanning system folder
// The simulation of a media loading broadcast, for the preservation of images can be viewed in Gallery
/*Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
sendBroadcast(intent);*/
} catch (Exception e) {
Toast.makeText(DrawTextOnImgActivity.this, "Save failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
DrawView
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
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.widget.ImageView;
public class DrawView extends ImageView {
private int color = Color.parseColor("#0000FF");
private float width = 4f;
private List<Holder> holderList = new ArrayList<Holder>();
private class Holder {
Path path;
Paint paint;
Holder(int color, float width) {
path = new Path();
paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(width);
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
}
}
public DrawView(Context context) {
super(context);
init();
}
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
holderList.add(new Holder(color, width));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (Holder holder : holderList) {
canvas.drawPath(holder.path, holder.paint);
}
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
holderList.add(new Holder(color,width));
holderList.get(holderList.size() - 1).path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
holderList.get(holderList.size() - 1).path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
invalidate();
return true;
}
public void resetPaths() {
for (Holder holder : holderList) {
holder.path.reset();
}
invalidate();
}
public void setBrushColor(int color) {
this.color = color;
}
public void setWidth(float width) {
this.width = width;
}
}
Layout (activity_draw_text_on_img)
<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"
android:background="#FFFFFF" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:background="#FFFFFF" >
<com.app.drawtextonimg.DrawView
android:id="#+id/iv_draw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:src="#drawable/rajamouli" />
</RelativeLayout>
<Button
android:id="#+id/btn_save"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:background="#000000"
android:text="#string/save"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/btn_resume"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#000000"
android:text="#string/resume"
android:textColor="#FFFFFF" />
</RelativeLayout>
Manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Project link
If I understand your question correctly, I think that you should remove this line from your Case.ACTION_MOVE.
iv_canvas.setImageBitmap(baseBitmap);
By doing this you are resetting your ImageView every time you move on the screen which will cause the ImageView to be just a blank
I wish to create a floating button which will hover over the entire Android screen. When the button or hovering icon is clicked, it should open a small popupwindow.
I was able to create the hovering icon using service class however I am unable to launch popupwindow. Whenever I click the floating icon, the error log says:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
/**
* Created by sejal on 17-Oct-15.
*/
public class bubble extends Service{
PopupWindow popw;
private WindowManager windowManager;
private ImageView floatingFaceBubble;
public void onCreate() {
super.onCreate();
floatingFaceBubble = new ImageView(this);
//a face floating bubble as imageView
floatingFaceBubble.setImageResource(R.drawable.bubble);
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
//here is all the science of params
final LayoutParams myParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
LayoutParams.TYPE_PHONE,
LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
myParams.gravity = Gravity.TOP | Gravity.LEFT;
myParams.x=0;
// add a floatingfacebubble icon in window
windowManager.addView(floatingFaceBubble, myParams);
try{
floatingFaceBubble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getpopuppwindow();
}
});
//for moving the picture on touch and slide
floatingFaceBubble.setOnTouchListener(new View.OnTouchListener() {
LayoutParams paramsT = myParams;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
private long touchStartTime = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
//remove face bubble on long press
/* if(System.currentTimeMillis()-touchStartTime> ViewConfiguration.getLongPressTimeout() && initialTouchX== event.getX()){
//// windowManager.removeView(floatingFaceBubble);
//// stopSelf();
// return false;
// } */
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touchStartTime = System.currentTimeMillis();
initialX = myParams.x;
initialY = myParams.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
myParams.x = initialX + (int) (event.getRawX() - initialTouchX);
myParams.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(v, myParams);
break;
}
return false;
}
});
} catch (Exception e){
e.printStackTrace();
}
}
//(ViewGroup) floatingFaceBubble.findViewById(R.id.pop)
private void getpopuppwindow() {
try {
System.out.print("111111");
LayoutInflater inflater = (LayoutInflater)bubble.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
System.out.print("222222");
View layout = inflater.inflate(R.layout.popup,(ViewGroup) floatingFaceBubble.findViewById(R.id.pop));
System.out.print("333333");
popw = new PopupWindow(layout ,300,100 ,true) ;
System.out.print("444444");
popw.showAtLocation(layout, Gravity.CENTER,0,0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
You should not do these ui operations in your service class. Because after you show your button service instance will be removed and there is no context when you click the button. I think you should follow similar approach like below.
Service Class:
Intent activityIntent = new Intent(context, MainActivity);
activityIntent.putExtra("showPopup", true);
context.startActivity(activityIntent);
Activity Class:
onCreate(){
boolean showPopUp = getIntent().getBooleanExtra("showPopup", false);
if(showPopUp){
// Show your popup here
}
}
I have an app that shows an image (ImageView). I want that when I touch the screen on the image, it draws a line in the same point where I touched.
With this code I can't do it but i think that it has a logical thought.
Could you help me please?
Thanks
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;
public class Cronograma extends Activity{
public boolean touched=false;
public float touched_x=0, touched_y=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cronograma);
}
public void onDraw(Canvas canvas){
Paint pincel = new Paint();
pincel.setColor(Color.BLUE);
pincel.setStrokeWidth(8);
pincel.setStyle(Style.STROKE);
if (touched==true)
canvas.drawLine(touched_x, touched_y, touched_x+5, touched_y, pincel);
}
public boolean onTouchEvent (MotionEvent event){
touched_x = event.getX();
touched_y = event.getY();
int action = event.getAction();
switch (action){
case MotionEvent.ACTION_DOWN:
Toast toast = Toast.makeText(getApplicationContext(), "La coordenada x es " + touched_x + " y la coordenada y es " + touched_y , Toast.LENGTH_SHORT);
toast.show();
touched=true;
break;
}
return false;
}
}