Moving image with touch events - android

I need a sample code for when we move(touch) a image from left to right and right to left. Please help me.
Regards,
chakri

try this code...
this is your main activity class
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int eid = event.getAction();
switch (eid) {
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
int x = (int) event.getRawX();
int y = (int) event.getRawY();
mParams.leftMargin = x-50;
mParams.topMargin = y-50;
imageView.setLayoutParams(mParams);
break;
default:
break;
}
return true;
}
});
}
}
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" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="126dp"
android:layout_marginTop="168dp"
android:src="#drawable/ic_launcher" />
</RelativeLayout>

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

Unable to start Android Service

I am trying to make a build a simple service kinda facebook chathead but for some reason i am not able to start the service, whenever i click on the start service button nothing happens. if someone can help me here and tell me what am i doing wrong, i would really appreciate it. Thanks
FloatService.java
package com.example.justeen.floatexample;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
public class FloatService extends Service{
private WindowManager windowManager;
private ImageView floatIcon;
#Override public IBinder onBind(Intent intent) {
// Not used
return null;
}
#Override public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
floatIcon = new ImageView(this);
floatIcon.setImageResource(R.drawable.android_head);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(floatIcon, params);
try {
floatIcon.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
return true;
case MotionEvent.ACTION_MOVE:
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(floatIcon, params);
return true;
}
return false;
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (floatIcon != null) windowManager.removeView(floatIcon);
}
}
Activity.Java
package com.example.justeen.floatexample;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
public class HelloWorldActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world);
Bundle bundle = getIntent().getExtras();
if(bundle != null && bundle.getString("LAUNCH").equals("YES")) {
startService(new Intent(HelloWorldActivity.this, FloatService.class));
Button launch = (Button) findViewById(R.id.button1);
launch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(HelloWorldActivity.this, FloatService.class));
}
});
Button stop = (Button) findViewById(R.id.button2);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(HelloWorldActivity.this, FloatService.class));
}
});
}
}
#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_hello_world, menu);
return true;
}
}
Manifet.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.justeen.floatexample" >
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HelloWorldActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.justeen.floatexample.FloatService"
android:enabled="true">
</service>
</application>
</manifest>
You have to remove the bundle check since it is kind of a copy paste without sense. When the onCreate is called first in the main activity, the Bundle value will be null so this is not attaching the click listeners to your service. Remove the bundle check and everything will work.

Switch between activities in Android?

I want to switch between my Main Actvity and my second Activity, but whenever I do it the app shuts down.
So after i click the button1 "Neues Feld", the App should switch to the second activity: feldlayout.class with the layout: feldlayout.xml! The activities are liested in the Android_MAnifest, that's also not the problem...
Thank you for the help! It's working now! I made a new View class, added it to the layout and then it worked fine!
Main Class
package com.example.volleyballapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
public class Main_Layout extends Activity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_layout);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(myhandler);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main__layout, menu);
return true;
}
View.OnClickListener myhandler = new View.OnClickListener(){
public void onClick(View v) {
if(v==b1){
Intent i = new Intent(Main_Layout.this, feldlayout.class);
startActivity(i);
}
}
};}
Main Layout
<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="#drawable/background2"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".Main_Layout" >
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:text=" "
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/farbe" />
<Button
android:id="#+id/button1"
style="#style/ButtonText"
android:layout_below="#id/textView"
android:layout_centerHorizontal="true"
android:background="#drawable/bnt_black"
android:onClick="NeuesFeldClick"
android:text="Neues Feld" />
<TextView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=" "
android:id="#+id/textView2"
android:textColor="#color/farbe"
android:layout_below="#id/button1"/>
<Button
android:id="#+id/button2"
style="#style/ButtonText"
android:layout_below="#id/textView2"
android:layout_centerHorizontal="true"
android:background="#drawable/bnt_black"
android:onClick="LetztesFeldClick"
android:text="Letztes Feld" />
<TextView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=" "
android:id="#+id/textView3"
android:textColor="#color/farbe"
android:layout_below="#id/button2"/>
<Button
android:id="#+id/button3"
style="#style/ButtonText"
android:layout_below="#id/textView3"
android:layout_centerHorizontal="true"
android:background="#drawable/bnt_black"
android:onClick="SavesClick"
android:text="Gespeicherte Felder" />
</RelativeLayout>
Second Activity
package com.example.volleyballapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
public class feldlayout extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feldlayout);
}
private Paint paint = new Paint();
private Path path = new Path();
int count = 1;
public feldlayout(Context context, AttributeSet attrs) {
super();
paint.setAntiAlias(true);
paint.setStrokeWidth(6f); //Breite des Strichs
paint.setColor(Color.BLACK); //Farbe des Strichs
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
protected void onDraw(Canvas canvas) {
if ((count%2 != 0)){
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:
count++;
if(count%2 != 1){
path.moveTo(eventX, eventY);
return true;
}
if(count%2 != 0){
path.lineTo(eventX, eventY);
break;
}
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
private void invalidate() {
// TODO Auto-generated method stub
}
}
It's just i tried. your code is working. The problem is you call Constructor in the second Activity. Below one.
public feldlayout(Context context, AttributeSet attrs) {
super();
paint.setAntiAlias(true);
paint.setStrokeWidth(6f); //Breite des Strichs
paint.setColor(Color.BLACK); //Farbe des Strichs
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
Please remove this constructor and try again.
Note
Just create a separate class and call the constructor there.

Update Progressbar according to ImageSwitcher progress

I currently have implemented an ImageSwitcher in my app, which slides through an array of pictures. Now I want to have a ProgressBar under the picture which shows on which position we are in the collection so the user gets a feeling of how much pictures are left.
Is this possible? Can I have some advices on how I might implement this?
Picture:
progress
[--|--------]
My ImageSwticher:
package com.example.cfaslides;
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.Animation;
import android.view.animation.Animation.AnimationListener;
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.ProgressBar;
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.av_01,
R.drawable.av_02,
R.drawable.av_03,
R.drawable.av_04,
R.drawable.av_05
};
int curIndex=0;
int maxIndex = 4; //# imageList -1
int downX, upX;
private Animation mIn1, mOut1, mIn2, mOut2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slider);
final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.progressB);
mProgressBar.setProgress(0);
mProgressBar.setMax(maxIndex);
mProgressBar.setVisibility(View.VISIBLE);
mIn1 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_in_left);
mOut1 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_out_right);
mIn2 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_in_right);
mOut2 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_out_left);
AnimationListener mAnimListener = new AnimationListener() {
public void onAnimationEnd(Animation animation) {
// the in animation has ended so update the ProgressBar with the new
// progress
mProgressBar.setProgress(curIndex); // I don't know your progress?!?
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
// rest of the callbacks
};
//set this listener for the both of the in animations
mIn1.setAnimationListener(mAnimListener);
mIn2.setAnimationListener(mAnimListener);
// rest of the onCreate method
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(l2_AltInvestActivity.this,android.R.anim.slide_in_left));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_out_right));
//curIndex current image index in array viewed by user
curIndex--;
if (curIndex < 0) {
curIndex = maxIndex; //maximum
}
//imageList :-image list array
imageSwitcher.setImageResource(imageList[curIndex]);
//GalleryActivity.this.setTitle(curIndex);
}
else if (downX -upX > -100) {
curIndex++;
if (curIndex > maxIndex) {
curIndex = 0;
}
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_in_right));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(l2_AltInvestActivity.this,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
Slider:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ProgressBar
android:id="#+id/progressB"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageSwitcher android:id="#+id/switcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
>
</ImageSwitcher>
</RelativeLayout>
now i like to have an progress bar under the picture which shows on
which position we are in the collection. so that someone gets a
feeling how much pictures are left.
Place a ProgressBar in your R.layout.slider layout file
Make the four different Animations that you used for the ImageSwitcher's transitions as fields in your Activity and also set an AnimationListener for each of them:
//...
private Animation mIn1, mOut1, mIn2, mOut2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slider);
final ProgressBar = (ProgressBar) findViewById(R.id.theIdOfTheProgressBar);
mIn1 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_in_left);
mOut1 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_out_right);
mIn2 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_in_right);
mOut2 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_out_left);
AnimationListener mAnimListener = new AnimationListener() {
public void onAnimationEnd(Animation animation) {
// the in animation has ended so update the ProgressBar with the new
// progress
mProgressBar.setProgress(curIndex); // I don't know your progress?!?
}
// rest of the callbacks
});
//set this listener for the both of the in animations
mIn1.setAnimationListener(mAnimListener);
mIn2.setAnimationListener(mAnimListener);
// rest of the onCreate method
In the onTouch method update the ImageSwitcher with the proper animations(from mIn1, mOut1, mIn2, mOut2)

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