draw a line on an image (ImageView) - android

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

Related

Android: Draw text on ImageView with finger touch

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

How to operate Android OS with screen coordinates

I have coordinates of screen and I want to tell operating system to perform that operation which OS is supposed to perform on touch of screen on that coordinates.
Just like cicret somehow tells mobile phone that what to do. While user is not directly interacting with mobile phone.
Plz tell me anything if you know about it.
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
public class MainActivity extends Activity
{
StringBuilder stringBuilder = new StringBuilder();
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.textView = (TextView) findViewById( R.id.strXY );
this.textView.setText("X: ,Y: ");//texto inicial
this.textView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
stringBuilder.setLength(0);
if (arg1.getAction() == MotionEvent.ACTION_MOVE) {
stringBuilder.append("Moving, X:" + arg1.getX() + ", Y:" + arg1.getY());
}
else {
stringBuilder.append("Stoped, X:" + arg1.getX() + ", Y:" + arg1.getY());
}
textView.setText(stringBuilder.toString());
return true;
}
});
}
}

Calling custom view from main activity.. Message in onDraw() is printed but custom view is not rendered

I have two classes - MainActivity.java and MainView.java.
I'm trying to render a custom view (defined in MainView.java) when screen is touched from the main activity.
My code is doing a funky thing. From the main page, when you touch the screen, it does NOT render the custom view I've specified in MainView.java - but still prints out a message I put in the onDraw() method, which should mean that onDraw() is being run. Why is my onDraw() method being run but its view doesn't render?
Also, both my onTouchEvent in MainActivity.java and MainView.java seems to respond at the same time, although the view I see is the only the activity_main.xml.
Please help :(
MainActivity.java
package com.example.owner.thesisapp;
import com.example.owner.thesisapp.MainView;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.media.AudioManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.media.SoundPool;
import android.view.View;
import android.graphics.Canvas;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity {
private static SoundPool soundPool;
private static HashMap soundPoolMap;
private static int S1 = R.raw.a3v1;
private static int S2 = R.raw.c3v1;
private static int S3 = R.raw.dsharp3v1;
private static int S4 = R.raw.fsharp3v1;
private int soundID;
private boolean isSoundLoaded = false;
public MainView mainView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainView = (MainView) findViewById(R.id.main_view);
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
isSoundLoaded = true;
}
});
soundID = soundPool.load(this, R.raw.fsharp3v1, 1);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
if (isSoundLoaded) {
soundPool.play(soundID, 1f, 1f, 1, 0, 1f);
Log.d("Test", "Played sound");
}
mainView.postInvalidate();
return false;
}
#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);
}
#Override
// Keep landscape orientation
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
}
MainView.java
package com.example.owner.thesisapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
/**
* Created by Owner on 6/1/2015.
*/
public class MainView extends View {
Bitmap stillWave;
int iy = 0;
public MainView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
stillWave = BitmapFactory.decodeResource(getResources(), R.drawable.wave);
setWillNotDraw(false);
Log.d("MAINVIEW: Is this ran?", " ");
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("Action DOWN!", " ");
iy = 0;
this.invalidate();
case MotionEvent.ACTION_MOVE:
Log.d("Action MOVE!", " ");
case MotionEvent.ACTION_UP:
Log.d("Action UP!", " ");
}
return false;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("MAINVIEW ONDRAW: Is this ran?", " ");
int width = canvas.getWidth();
int height = canvas.getHeight();
//set background
Rect wBackground = new Rect();
wBackground.set(0, 0, width, height);
Paint pBackground = new Paint();
pBackground.setStyle(Paint.Style.FILL);
pBackground.setColor(Color.BLACK);
canvas.drawRect(wBackground, pBackground);
//Log.d("garo, sero", width + " " + height);
//set Wave
Paint pWave = new Paint();
pWave.setStyle(Paint.Style.FILL_AND_STROKE);
pWave.setColor(Color.WHITE);
pWave.setStrokeWidth(10);
pWave.setStrokeCap(Paint.Cap.ROUND);
int waveFlucMin = -100;
int waveFlucMax = 100;
float[] coords = new float[width * 2];
for (int ix = 0; ix < width; ix++) {
int yoffset = waveFlucMin + (int) (Math.random() * ((waveFlucMax - waveFlucMin) + 1));
coords[2 * ix] = (float) ix;
coords[2 * ix + 1] = (float) iy + yoffset;
}
//Log.d("Coordinates x?", coords[1] + " " + coords[3] + " " + coords[5] + " " + coords[7] + " " + coords[301] + " " + coords[303] + " ");
//Log.d("Coordinates y?", coords[0] + " " + coords[2] + " " + coords[4] + " " + coords[6] + " " + coords[300] + " " + coords[302] + " ");
//Log.d("Generating?", "YES, generating forloop : " + iy);
//wait a second between each wave generation
/*
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
drawWave(coords, width, pWave, canvas);
if (iy < height) {
iy += 10;
invalidate();
} else {
//do nothing - finish onDraw() call.
}
}
private void drawWave(float[] coords, int width, Paint pWave, Canvas canvas) {
canvas.drawPoints(coords, 0, width*2, pWave);
}
}
activity_main.xml
<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" tools:context=".MainActivity">
<com.example.owner.thesisapp.MainView
android:id="#+id/main_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#111C64"/>
The problem is in your layout. Both your custom View and the ImagView are, since your are using a RelativeLayout, aligned to the Top left. The z order in this case put the ImageView on top on your custom View and, since it is taking the whole screen, you can't see your custom view.

How to create a button using onTouch?

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

Full Screen Gallery Code

i just find some solution for an full screen gallery implementation but i cant get the code work. maybe anyone can help me about that.
I need a full screen image switcher without an thumbnail gallery where i can switch between the pictures with swiping with finger.
i got the following error:
firstActivity cannot be resolved to a type
slide_in_right cannot be resolved or is not a field
slide_out_left cannot be resolved or is not a field
i am pretty new to android coding :)
Please help me
package com.example.prog;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ViewSwitcher;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.view.Window;
import android.content.Context;
public class l2_AltInvestActivity extends Activity implements ViewFactory {
ImageSwitcher imageSwitcher;
Integer[] imageList = {
R.drawable.fr_l1_01,
R.drawable.fr_l1_02,
R.drawable.fr_l1_03,
R.drawable.fr_l1_04,
R.drawable.fr_l1_05
};
int curIndex=0;
int downX, upX;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mmenutest);
imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
imageSwitcher.setFactory(this);
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));
imageSwitcher.setImageResource(imageList[curIndex]);
imageSwitcher.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(firstActivity.this,android.R.anim.slide_in_left));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(firstActivity.this,android.R.anim.slide_out_right));
//curIndex current image index in array viewed by user
curIndex--;
if (curIndex < 0) {
curIndex = 5; //maximum
}
//imageList :-image list array
imageSwitcher.setImageResource(imageList[curIndex]);
//GalleryActivity.this.setTitle(curIndex);
}
else if (downX -upX > -100) {
curIndex++;
if (curIndex > 4) {
curIndex = 0;
}
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.slide_in_right));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.slide_out_left));
imageSwitcher.setImageResource(imageList[curIndex]);
//GalleryActivity.this.setTitle(curIndex);
}
return true;
}
return false;
}
});
} //END onCreate
#Override
public View makeView() {
ImageView i = new ImageView(this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
i.setBackgroundColor(0xFF000000);
return i;
} //END makeView
} // END Class
Use Current Activity Context to access resources instead of Any other activity as in current code you are trying to access Animation resources by passing firstActivity.this .
imageSwitcher.setInAnimation(AnimationUtils.
loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_in_left));
imageSwitcher.setOutAnimation(AnimationUtils.
loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_out_right));
use l2_AltInvestActivity.this instead of firstActivity.this

Categories

Resources