How to Track all gestures on ENTIRE android screen? - java

How do I track all gestures on an entire application screen. I was struggling with adding a gesture detector to the entire screen of my application. I am using gesturedetector compat to get gestures from the layout however when I tap or double tap the button and edit text gesturedetector does not detect the gesture on the view. Is it possible to have all tap,swipes,gestures on the ENTIRE screen as opposed to only the layout. If there is a better solution to tracking all touches,swipes,taps please let me know I have struggling with this for weeks.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private GestureDetectorCompat mGestureDetector;
private TextView touchCheckText;
private TextView singleTapText;
private TextView doubleTapText;
private static final String TAG = "Gesture ";
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction()!=KeyEvent.ACTION_DOWN)
Log.i("key pressed", String.valueOf(event.getKeyCode()));
return super.dispatchKeyEvent(event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGestureDetector = new GestureDetectorCompat(this,new GestureListener());
touchCheckText = (TextView) findViewById(R.id.touchCheckTextView);
scrollText = (TextView) findViewById(R.id.scrollTextView);
singleTapText = (TextView) findViewById(R.id.singleTapTextView);
doubleTapText = (TextView) findViewById(R.id.doubleTapTextView);
}
private class GestureListener extends GestureDetector.SimpleOnGestureListener{
#Override
public boolean onDoubleTap(MotionEvent e) {
int x = (int) e.getX();
int y = (int) e.getY();
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
Log.e(TAG, "in on onDoubleTap Event");
doubleTapText.setBackgroundColor(Color.GREEN);
return super.onDoubleTap(e);
}
#Override
public boolean onDown(MotionEvent e) {
touchCheckText.setText("TOUCHING!");
return super.onDown(e);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
int x = (int) e.getX();
int y = (int) e.getY();
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
singleTapText.setBackgroundColor(Color.GREEN);
Log.e(TAG, "Single Tap "+ts+" x:"+x+" y:"+y);
singleTapText.postDelayed(new Runnable() {
#Override
public void run() {
// change color in here
singleTapText.setBackgroundColor(Color.TRANSPARENT);
}
}, 100);
return super.onSingleTapConfirmed(e);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
switch ( event.getAction() ) {
case MotionEvent.ACTION_UP:
Log.e("onTouch","Released");
doubleTapText.setBackgroundColor(Color.TRANSPARENT);
touchCheckText.setText("No Longer Touching");
break;
}
return super.onTouchEvent(event);
}
}

Related

Real-time graph with AChartEngine: Chart plotting last retrieved value from cloud database even when no value is sent to cloud

I am using AChartEngine to plot values obtained from Ubidots in real-time. The graph is retrieving values in real-time however when no value is being sent on Ubidots, the last retrieved value sent on Ubidots is being plotted again as shown in the screenshot.
Here are my codes:
LineGraph.java:
public class LineGraph {
private GraphicalView view;
private TimeSeries dataset = new TimeSeries("LDR Values");
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYSeriesRenderer renderer = new XYSeriesRenderer(); // This will be used to customize line 1
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); // Holds a collection of XYSeriesRenderer and customizes the graph
public LineGraph()
{
// Add single dataset to multiple dataset
mDataset.addSeries(dataset);
// Customization time for line 1!
renderer.setColor(Color.BLUE);
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
renderer.setDisplayChartValues(true);
renderer.setChartValuesSpacing(10);
// mRenderer: renderer that controls the full charts and add the single renderer for each series:
// Enable Zoom
//mRenderer.setZoomButtonsVisible(true);
mRenderer.setMarginsColor(Color.argb(0x00, 0xff, 0x00, 0x00));
mRenderer.setXTitle("Day #");
mRenderer.setYTitle("LDR Values");
mRenderer.setYAxisMax(30000);
mRenderer.setYAxisMin(10000);
mRenderer.setShowGrid(true);
// Add single renderer to multiple renderer
mRenderer.addSeriesRenderer(renderer);
}
public GraphicalView getView(Context context)
{
view = ChartFactory.getLineChartView(context, mDataset, mRenderer);
return view;
}
public void addNewPoints(Point p)
{
dataset.add(p.getX(), p.getY());
}
}
Point.java:
public class Point {
private int x;
private int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
private static GraphicalView view;
private LineGraph line = new LineGraph();
private static Thread thread;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
thread = new Thread() {
public void run()
{
for (int i = 0; i <1000; i++)
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Point p = UbidotsData.getDataFromReceiver(i); // We got new data!
line.addNewPoints(p); // Add it to our graph
view.repaint();
}
}
};
thread.start();
}
#Override
protected void onStart() {
super.onStart();
view = line.getView(this);
setContentView(view);
}
}
UbidotsData.java
public class UbidotsData {
//private static Context context;
public static Point getDataFromReceiver(int x)
{
ApiClient api = new ApiClient("XXXXXXXXXXXXXXXXXXX");
Variable ldr = api.getVariable("XXXXXXXXXXXXXXXXXXX");
Value[] values = ldr.getValues();
int newValue = (int) values[0].getValue();
if(newValue>22000){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(Context.getContext(), notification);
mp.start();
}
return new Point(x, newValue);
}
}
Furthermore, when I close the app and open it again, it starts to plot the same data retrieved from Ubidots previously (when I ran the program while it was fetching data in real-time). How do I make the data permanent in the graph instead of having the graph plot it again when I open it? Should I be using AsyncTask instead of Thread in this case?
To make it clearer, it is this line which fetches the value:
int newValue = (int) values[0].getValue();

Create stream from audio file in Android

The use case is this, in Android (above Kit Kat): open a stream from an audio file, get its properties, modify the memory buffer and play the result.
I would like to know how to 1) properly create the stream from the audio file; 2) get its properties (channels, encoding, length) like for the javax.sound.sampled.AudioFormat, but using methods from the android.media framework.
I know how to build a stream from binary, add audio properties to it then playing it. I would like to do the other way and extract these properties (channels, encoding) from the existing sound file header, using latest classes of the Android framework.
Thanks!
Here is full streaming class use this :
public class MainActivity extends Activity implements OnClickListener,
OnTouchListener, OnCompletionListener, OnBufferingUpdateListener {
private Button btn_play, btn_pause, btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://songspkcompilations.com/indian/soulfularijit/%5BSongs.PK%5D%2012%20-%20Mickey%20Virus%20-%20Tose%20Naina.mp3";
private static final int MINUTES_IN_AN_HOUR = 60;
private static final int SECONDS_IN_A_MINUTE = 60;
private final Handler handler = new Handler();
private boolean is_loading = true;
private boolean is_stopped = false;
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
private TextView txtTime;
private ProgressBar musicProgress;
private ImageView artistImg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize_Controls();
}
private void initialize_Controls() {
btn_play = (Button) findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button) findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button) findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
musicProgress = (ProgressBar) findViewById(R.id.progress);
artistImg = (ImageView) findViewById(R.id.artistImg);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
txtTime = (TextView) findViewById(R.id.time);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar) v;
mediaPlayer
.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress());
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
// Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
if (is_stopped) {
is_stopped = false;
mediaPlayer.seekTo(0);
}
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
if (is_loading) {
is_loading = false;
musicProgress.setVisibility(View.GONE);
artistImg.setVisibility(View.VISIBLE);
}
int progress = (int) (((float) mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100);
int remainSec = (lengthOfAudio - mediaPlayer.getCurrentPosition()) / 1000;
seekBar.setProgress(progress);
txtTime.setText("" + timeConversion(remainSec));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
if (mediaPlayer != null) {
mediaPlayer.pause();
is_stopped = true;
}
seekBar.setProgress(0);
seekBar.setSecondaryProgress(0);
txtTime.setText("" + timeConversion(lengthOfAudio / 1000));
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
private void pauseAudio() {
if (mediaPlayer != null) {
mediaPlayer.pause();
}
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
if (mediaPlayer != null) {
mediaPlayer.start();
}
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
private static String timeConversion(int totalSeconds) {
int hours = totalSeconds / MINUTES_IN_AN_HOUR / SECONDS_IN_A_MINUTE;
int minutes = (totalSeconds - (hoursToSeconds(hours)))
/ SECONDS_IN_A_MINUTE;
int seconds = totalSeconds
- ((hoursToSeconds(hours)) + (minutesToSeconds(minutes)));
return hours + ":" + minutes + ":" + seconds;
}
private static int hoursToSeconds(int hours) {
return hours * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE;
}
private static int minutesToSeconds(int minutes) {
return minutes * SECONDS_IN_A_MINUTE;
}
class PlayTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
// Log.e("Error", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
playAudio();
updateSeekProgress();
}
}
#Override
protected void onResume() {
super.onResume();
new PlayTask().execute();
}
#Override
public void onBackPressed() {
super.onBackPressed();
pauseAudio();
finish();
}
}

Use a checkbox to allow the user to save the values in the textviews and editview so they are seen immedietly upon reopening the application.

Very new to android java programming. I created a car payment calculator application for one of my classes and I am trying to create a checkbox that the user can check so that all the values stored in the TextViews and EditViews remain the same when the application is opened again.
Here is my activity:
public class MainActivity extends Activity implements OnClickListener,
OnEditorActionListener, OnItemSelectedListener, OnFocusChangeListener,
OnCheckedChangeListener {
private TextView payment;
private TextView interest;
private EditText principle;
private TextView interestText;
private CheckBox interestBox;
private EditText years;
private TextView apr;
Button plusbutton;
Button minusbutton;
private static String TAG = "CAR";
private Spinner period;
private double aprPercent;
private int t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
this.getReferences();
this.setListeners();
}
#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, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getReferences() {
payment = (TextView) findViewById(R.id.paymentLabel);
interest = (TextView) findViewById(R.id.interestLabel);
apr = (TextView) findViewById(R.id.aprLabel);
aprPercent = Double.parseDouble(apr.getText().toString());
interestText = (TextView) findViewById(R.id.interestText);
interestBox = (CheckBox) findViewById(R.id.checkBox1);
interestBox.setChecked(false);
principle = (EditText) findViewById(R.id.principleEditText);
years = (EditText) findViewById(R.id.yearsEditText);
period = (Spinner) findViewById(R.id.spinner1);
minusbutton = (Button) findViewById(R.id.minusbutton);
plusbutton = (Button) findViewById(R.id.plusbutton);
ArrayAdapter<CharSequence> adapter = ArrayAdapter
.createFromResource(this, R.array.split_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
period.setAdapter(adapter);
// principle.setOnFocusChangeListener(this);
Log.d(TAG, "getReferences principle: " + principle.getText()
+ " years:" + years.getText());
}
public void setListeners() { // where the event being consumed will be
// responding
principle.setOnFocusChangeListener(this);
principle.setOnEditorActionListener(this);
years.setOnFocusChangeListener(this);
years.setOnEditorActionListener(this);
interestBox.setOnCheckedChangeListener(this);
period.setOnItemSelectedListener(this);
Log.d(TAG, "setListeners principle: " + principle.getText() + " years:"
+ years.getText());
}
public void setPeriodValue() {
if (period.getSelectedItem().toString().equalsIgnoreCase("Monthly")) {
t = 12;
} else if (period.getSelectedItem().toString()
.equalsIgnoreCase("Quarterly")) {
t = 4;
} else if (period.getSelectedItem().toString()
.equalsIgnoreCase("Annually")) {
t = 1;
}
}
public void updateResults() {
double dblPrinciple = Double
.parseDouble(principle.getText().toString());
double dblYears = Double.parseDouble(years.getText().toString());
double num, denom, dblPayment;
double r = aprPercent / 100;
NumberFormat nf = NumberFormat.getNumberInstance();
NumberFormat curr = NumberFormat.getCurrencyInstance();
apr.setText(nf.format(aprPercent));
setPeriodValue();
num = (r / t);
denom = (1 - Math.pow((1 + num), (t * -dblYears)));
dblPayment = dblPrinciple * (num / denom);
payment.setText(curr.format(dblPayment));
interest.setText(curr
.format((dblPayment * t * dblYears) - dblPrinciple));
}
public void onFocusChange(View v, boolean hasfocus) {
Log.d(TAG, "Focus Change principle: " + principle.getText() + " years"
+ years.getText());
switch (v.getId()) {
case R.id.principleEditText:
case R.id.yearsEditText:
updateResults();
default:
updateResults();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(interestBox.isChecked()) {
interest.setVisibility(View.VISIBLE);
interestText.setVisibility(View.VISIBLE);
}
else {
interest.setVisibility(View.INVISIBLE);
interestText.setVisibility(View.INVISIBLE);
}
if (interestBox.isChecked()!=true){
interest.setVisibility(View.INVISIBLE);
interestText.setVisibility(View.INVISIBLE);
}
else {
interest.setVisibility(View.VISIBLE);
interestText.setVisibility(View.VISIBLE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
updateResults();
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
updateResults();
return false;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.minusbutton:
if (aprPercent == 1) {
break;
} else {
aprPercent = aprPercent - 1.0;
updateResults();
break;
}
case R.id.plusbutton:
if (aprPercent == 20) {
break;
} else {
aprPercent = aprPercent + 1.0;
updateResults();
break;
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
updateResults();
}
My guess is that I have to do something with sharedprefs but I'm not exactly sure how to go about it. Any push in the right direction would be great. thank you.
Use getSharedPreferences(...).edit().putString(...).commit() to store values in "onPause()" and again use getSharedPreferences(...).getString(...) to retrieve information in your "onResume()". It's just that easy.
You will have to read how to save your Activity data. In my opinion you should not use checkbox to save this data but save it by default.
To save your data while the screen rotate you will have to check the OnSaveInstanceState and OnRestoreInstanceState like in this post. It will handle the data when rotated too.
To save your data for a longer time (changing of applications, closing application), You will have to use the Android preferences but check how works the lifecycle of an Activity. Basically you will need to save in the OnPause or OnDestroy and reload it in the OnResume or OnCreate.
Concerning the preferences you have a nice tutorial on the Vogella Website
//Get Data
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String url = settings.getString("url", "n/a");
//Save Data
Editor edit = preferences.edit();
edit.putString("username", "new_value_for_user");
edit.apply();

How to swipe zoomed image using ImageViews and PageAdapter

I am trying to create an image viewer which can load images from given URLs.The code below implement the User Interface.
My intention is to let user Zoom the image and move to next image with a Swipe event.But the problem is that when i zoom and then swipe , instead of showing the remaining portion , it moves to the next image.
I tried using requestDisallowInterceptTouchEvent in TouchImageView's(https://github.com/MikeOrtiz/TouchImageView) onTouchListener .After this the remaining portion could show but now i cannot go to the next page. I was wondering how this can be achieved as the event can only go to either TouchView or PageAdapter
public class PageActivity extends Activity {
private int numPages = 33;
private TouchImageView[] imageViews = new TouchImageView[numPages];
private String URL = "http://www.smbc-comics.com/comics/200905";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewPager viewPager = new ViewPager(this);
for (int i = 0; i < numPages; i++) {
imageViews[i] = new TouchImageView(this);
imageViews[i].setBackgroundResource(R.drawable.banke);
imageViews[i].setMaxZoom(4f);
}
setContentView(viewPager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
}
#SuppressWarnings("unused")
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return numPages;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((TouchImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = PageActivity.this;
String pageURL = URL;
if (imageViews[position].getDrawable() == null) {
ImageFetcher imagefetcher = new ImageFetcher();
imagefetcher.execute(
pageURL + String.format("%02d", position+1) + ".gif",
String.valueOf(position));
}
((ViewPager) container).addView(imageViews[position], 0);
return imageViews[position];
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((TouchImageView) object);
imageViews[position].setImageDrawable(null);
}
}
public class ImageFetcher extends AsyncTask<String, Integer, Drawable> {
int fillthisPos;
public Drawable doInBackground(String... urls) {
try {
InputStream is = (InputStream) new URL(urls[0]).getContent();
fillthisPos = Integer.parseInt(urls[1]);
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(Drawable result) {
super.onPostExecute(result);
imageViews[fillthisPos].setImageDrawable(result);
result = null;
}
}
}
You can add following code in TouchImageView class:
public boolean isZoomed () {
return (normalizedScale > minScale);
}
private void onSwipeEvent(MotionEvent event) {
boolean zoomed = this.isZoomed();
if (!zoomed && (swipeLen > 0)) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
swipeStartPos = (int) event.getRawX();
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
int distance = ((int) event.getRawX()) - swipeStartPos;
int swipeVector = SWIPE_RIGHT;
if (distance < 0) swipeVector = SWIPE_LEFT;
if (Math.abs(distance) > swipeLen) {
onSwipeHandler.onSwipe(swipeVector);
swipeStartPos = (int) event.getRawX();
this.setScaleX(1f);
}
else {
int swipeStDist = swipeLen - Math.round(((swipeLen / 100) * 50));
if (Math.abs(distance) > swipeStDist) {
this.setScaleX(0.98f);
}
}
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
swipeStartPos = (int) event.getRawX();
this.setScaleX(1f);
}
}
}
public static int SWIPE_LEFT = 0;
public static int SWIPE_RIGHT = 1;
public int swipeStartPos = 0;
public onSwipeListener onSwipeHandler = new onSwipeListener() {
public void onSwipe(int vector) {}
};
public static int swipeLen = 0;
public void setOnSwipeListener(onSwipeListener c, int swipeLength) {
onSwipeHandler = c;
swipeLen = swipeLength;
}
public interface onSwipeListener {
public void onSwipe(int vector);
}
And also in TouchImageView below line 636 add onSwipeEvent(event) like this:
......
setImageMatrix(matrix);
onSwipeEvent(event);
//
// indicate event was handled
//
return true;
...........
After this from you code you can add swipe event listener, like this:
imageView.setOnSwipeListener(new TouchImageView.onSwipeListener() {
#Override
public void onSwipe(int vector) {
if (vector == TouchImageView.SWIPE_LEFT) {
Log.d("swipe", "swipe left!");
}
else if (vector == TouchImageView.SWIPE_RIGHT) {
Log.d("swipe", "swipe right!");
}
}
}, 200); //length of swiping - 200 dip
This onSwipeListener ignore onswipe where image is zoomed+. It work for me.

how to make android flipper animation using onFling()?

I'm having trouble in adding a little animation in onfling method. Everything is working just fine. Flipping pages left to right and right to left is done but there's no animation. I tried various things but couldn't get the animation working. Please guide me how can I add flipper animation or swipe animation. Here is the code:
public class MainActivity extends CustomTitlebarActivityBase {
// some random variables..
// detect swipe left/right
private GestureDetector gestureDetector;
private MyGestureListener gestureListener;
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "Creating MainActivity");
super.onCreate(savedInstanceState, true);
setContentView(R.layout.main_view);
// create related objects
gestureListener = new MyGestureListener(MainActivity.this);
gestureDetector = new GestureDetector( gestureListener );
documentViewManager = new DocumentViewManager(this);
documentViewManager.buildView();
myContentManager = new myContentManager(documentViewManager);
// force the screen to be populated
myContentManager.updateText(true);
}
// there are some other methods
/** user swiped left */
public void next() {
if (getDocumentViewManager().getDocumentView().isPageNextOkay()) {
CurrentPageManager.getInstance().getCurrentPage().next();
}
}
/** user swiped left */
public void previous() {
if (getDocumentViewManager().getDocumentView().isPagePreviousOkay()) {
CurrentPageManager.getInstance().getCurrentPage().previous();
}
}
}
// here is the listener class
public class MyGestureListener extends SimpleOnGestureListener {
// measurements in dips for density independence
private static final int DISTANCE_DIP = 40;
private int scaledDistance;
private int minScaledVelocity;
private MainActivity mainActivity;
private boolean sensePageDownTap;
private static final String TAG = "MyGestureListener";
public MyGestureListener(MainActivity mainActivity) {
super();
this.mainActivity = mainActivity;
scaledDistance = CommonUtils.convertDipsToPx(DISTANCE_DIP);
minScaledVelocity = ViewConfiguration.get(mainActivity).getScaledMinimumFlingVelocity();
// make it easier to swipe
minScaledVelocity = (int)(minScaledVelocity*0.66);
}
#Override
public void onLongPress(MotionEvent e) {
// do something
}
// here is the onFling
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// get distance between points of the fling
double vertical = Math.abs( e1.getY() - e2.getY() );
double horizontal = Math.abs( e1.getX() - e2.getX() );
Log.d(TAG, "onFling vertical:"+vertical+" horizontal:"+horizontal+" VelocityX"+velocityX);
if ( vertical > scaledDistance ) {
return false;
}
// test horizontal distance and velocity
else if ( horizontal > scaledDistance && Math.abs(velocityX) > minScaledVelocity ) {
if (e1.getX() > e2.getX()) {
mainActivity.next();
}
// left to right swipe
else {
mainActivity.previous();
}
return true;
}
return false;
}
}
Try to implement OnGestureListener. Sample code is beloe
public class MyActivity extends Activity implements GestureDetector.OnGestureListener {
private GestureDetector gestureScanner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
this.gestureScanner = new GestureDetector(this);
}
#Override
public boolean dispatchTouchEvent(MotionEvent paramMotionEvent) {
super.dispatchTouchEvent(paramMotionEvent);
return this.gestureScanner.onTouchEvent(paramMotionEvent);
}
public boolean onDown(MotionEvent paramMotionEvent) {
return false;
}
public boolean onFling(MotionEvent paramMotionEvent1, MotionEvent paramMotionEvent2, float paramFloat1,
float paramFloat2) {
// your fling code goes here
return true;
}
public void onLongPress(MotionEvent paramMotionEvent) {
}
public boolean onScroll(MotionEvent paramMotionEvent1, MotionEvent paramMotionEvent2, float paramFloat1,
float paramFloat2) {
return false;
}
public void onShowPress(MotionEvent paramMotionEvent) {
}
public boolean onSingleTapUp(MotionEvent paramMotionEvent) {
return false;
}
}

Categories