Android - Imageviews make them visible again, dont work - android

I have a problem with my ImageViews.
At a certain time I disable it and make it invisible. Later in the program, but they should be re-enabled and visible. Unfortunately it does not work. I have often tried to find the bug with the debugger, but the corresponding code is not skipped. Nevertheless, the buttons in the app are not visible or enabled. Even the animated drawable does not start, even though it should. This should happen when calling from playanimation().
As this is my first app or program, the code is a bit unreadable.
Maybe can help me?
Here's the code:
I mean that part of the code:
case 1:
imageViewsleepbutton.setVisibility(View.VISIBLE);
imageViewfeedbutton.setVisibility(View.VISIBLE);
imageViewShowerbutton.setVisibility(View.VISIBLE);
imageViewPlaybutton.setVisibility(View.VISIBLE);
imageViewsleepbutton.setEnabled(true);
imageViewfeedbutton.setEnabled(true);
imageViewShowerbutton.setEnabled(true);
imageViewPlaybutton.setEnabled(true);
Settings.setLevel(2, context);
helper.setCorrectPet();
helper.playAnimation();
textviewStatus.setText(activity.getString(R.string.baby));
break;
In that class:
package at.android.virtualpet;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class TimerC{
//TODO Try-Catch Timer
private Handler handler;
Toast toast;
private ImageView imageViewsleepbutton;
private ImageView imageViewfeedbutton;
private ImageView imageViewShowerbutton;
private ImageView imageViewPlaybutton;
private TextView textviewStatus;
private int intervall;
private Helper helper;
private Context context;
Activity activity;
public TimerC(Context context, Activity activity, int intervall){
this.context = context;
this.activity = activity;
this.intervall = intervall;
}
public void startTimer() {
boolean b, resume;
b = Settings.getFirstStart(context);
resume = Settings.getResumeStatus(context);
handler = new Handler();
helper = new Helper(context, activity);
if (b == true) {
Settings.setFirstStart(false, context);
handler.postDelayed(timedTask, 45000); //45000
}
else {
if (resume == true) {
helper.resumeStats();
Settings.setResumeStatus(false, context);
}
handler.postDelayed(timedTask, intervall);
}
}
public void stopTimer() {
handler.removeCallbacks(timedTask);
}
private void changePet() {
int stufe;
int progress;
imageViewsleepbutton = (ImageView) activity.findViewById(R.id.ImageViewsleepbutton);
imageViewfeedbutton = (ImageView) activity.findViewById(R.id.imageViewfeedbutton);
textviewStatus = (TextView) activity.findViewById(R.id.textViewStatus);
imageViewShowerbutton = (ImageView) activity.findViewById(R.id.imageViewShowerButton);
imageViewPlaybutton = (ImageView) activity.findViewById(R.id.imageViewPlayButton);
stufe = Settings.getLevel(context);
progress = Settings.getLevelProgress(context);
if (progress <= 0 || stufe == 1) {
switch(stufe) {
case 1:
imageViewsleepbutton.setVisibility(View.VISIBLE);
imageViewfeedbutton.setVisibility(View.VISIBLE);
imageViewShowerbutton.setVisibility(View.VISIBLE);
imageViewPlaybutton.setVisibility(View.VISIBLE);
imageViewsleepbutton.setEnabled(true);
imageViewfeedbutton.setEnabled(true);
imageViewShowerbutton.setEnabled(true);
imageViewPlaybutton.setEnabled(true);
Settings.setLevel(2, context);
helper.setCorrectPet();
helper.playAnimation();
textviewStatus.setText(activity.getString(R.string.baby));
break;
case 2:
Settings.setLevel(3, context);
helper.setCorrectPet();
helper.playAnimation();
textviewStatus.setText(activity.getString(R.string.teen));
break;
case 3:
Settings.setLevel(4, context);
helper.setCorrectPet();
helper.playAnimation();
textviewStatus.setText(activity.getString(R.string.adult));
break;
}
Settings.setLevelProgress(1000, context);
}
}
private void changeStats() {
int hunger;
int progress;
int stufe;
int sleep;
int fun;
int dirty;
int level;
int xp;
boolean day;
boolean firststart;
Random randInt = new Random();
int promp = 1; //progress multiplikator
int minushunger = randInt.nextInt(4)+3;
int minussleep = 3;
int sleepnight = 15;
int hungernight = randInt.nextInt(3)+2;
int minusdirty = randInt.nextInt(4)+2;
int minusfun = randInt.nextInt(2)+2;
int dirtynight = minusdirty;
int funnight = minusfun;
hunger = Settings.getHunger(context);
progress = Settings.getLevelProgress(context);
fun = Settings.getFun(context);
dirty = Settings.getDirty(context);
stufe = Settings.getLevel(context);
sleep = Settings.getSleep(context);
level = Settings.getLevel(context);
firststart = Settings.getFirstStart(context);
xp = Settings.getXP(context);
day = Settings.getDay(context);
if ((firststart == false) && (level != 1)) {
if (day == true) {
hunger = hunger - minushunger;
sleep = sleep - minussleep;
dirty = dirty - minusdirty;
fun = fun - minusfun;
} else {
hunger = hunger - hungernight;
sleep = sleep + sleepnight;
dirty = dirty - dirtynight;
fun = fun - funnight;
}
if(sleep > 100) {
sleep = 100;
helper.wakeup();
}
if(hunger < -5 ) {hunger = -5;}
if(sleep < -5) {sleep = -5;}
if(hunger > 110) {hunger = 110;}
if(dirty < -15 ) {dirty = -15;}
if(fun < -15 ) {fun = -15;}
if(dirty > 110) {dirty = 110;}
if(fun > 110) {fun = 110;}
Settings.setSleep(sleep, context);
Settings.setHunger(hunger, context);
Settings.setDirty(dirty, context);
Settings.setFun(fun, context);
//promp = 1
if ((sleep < 0) && (hunger < 0) && (dirty < 20) && (fun < 20)) {promp = 0;};
if ((sleep > 90) && (hunger > 90) && (dirty > 75) && (fun > 75)) {promp = 2;};
switch(stufe) {
case 1:
//Stufe 1 ist Ei. Das Ei schlüpft automatisch nach x Sek
break;
case 2:
progress = progress - (5 * promp);
break;
case 3:
progress = progress - (4 * promp);
break;
case 4:
progress = progress - (3 * promp);
break;
}
xp = xp + 4*promp;
Settings.setXP(xp, context);
helper.setCorrectPet();
helper.checkLevel();
Settings.setLevelProgress(progress, context);
helper.checkStatus();
}
}
private Runnable timedTask = new Runnable(){
#Override
public void run() {
changePet();
changeStats(); //Werte ändern und Meldungen ausgeben
helper.updateprogress();
helper.updateDebugFields();
handler.postDelayed(timedTask, intervall);
}};
}
and the playanimation() in an other class. This class has context an the activity from MainActivity.
public void playAnimation() {
imageViewPet = (ImageView)activity.findViewById(R.id.imageViewPet);
if (imageViewPet.getDrawable() instanceof AnimationDrawable) {
animatedaotori = (AnimationDrawable)imageViewPet.getDrawable();
Handler handler = new Handler(activity.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
animatedaotori.start();
}
}, 1500);
}
}

Related

Lag when using Bluetooth Adapter in Android Studio

My project:
Controlling 3 stepper motors with bluetooth.
I'm using Android Studio for the app and Arduino to receive the bluetooth data and control the Steppers.
My Problem
When my Arduino receives the data it lags or misses some of the data.
Here is my ConnectedThread.java class used to communicate to the Arduino.
package com.example.a3axisrig;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.SystemClock;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static com.example.a3axisrig.MainActivityKt.MESSAGE_READ;
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private final Handler mHandler;
public ConnectedThread(BluetoothSocket socket, Handler handler) {
mmSocket = socket;
mHandler = handler;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
#Override
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if(bytes != 0) {
buffer = new byte[1024];
SystemClock.sleep(10); //pause and wait for rest of data. Adjust this depending on your sending speed.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(char input) {
//byte[] bytes = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(input);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
And here's my Activity class(TimelapseActivity.kt) that inflates the view with a joystick to control two motors and a Left and Right buttons to control a 3rd motor.
package com.example.a3axisrig
import android.R.attr.button
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
private lateinit var setButton: Button
private lateinit var doneButton: Button
private lateinit var backButton: Button
private lateinit var point1Button: Button
private lateinit var point2Button: Button
private lateinit var point3Button: Button
private lateinit var rightButton: Button
private lateinit var leftButton:Button
private var points: Int = 0
class TimelapseActivity : AppCompatActivity(), JoystickView.JoystickListener {
#SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_timelapse)
val joystick = JoystickView(this)
window.decorView.setBackgroundColor(Color.argb(255, 212, 212, 212));
setButton = findViewById(R.id.set_button)
doneButton = findViewById(R.id.done_button)
backButton = findViewById(R.id.back_button)
rightButton = findViewById(R.id.right_button)
leftButton = findViewById(R.id.left_button)
point1Button = findViewById(R.id.point1Button)
point2Button = findViewById(R.id.point2Button)
point3Button = findViewById(R.id.point3Button)
point1Button.setBackgroundColor(Color.BLUE)
point2Button.setBackgroundColor(Color.BLUE)
point3Button.setBackgroundColor(Color.BLUE)
setButton.setOnClickListener { view: View ->
points++
updatePoints()
if (mConnectedThread != null) { //First check to make sure thread created
if (points==1) mConnectedThread!!.write('i') else if (points ==2)mConnectedThread!!.write('o')
}
}
doneButton.setOnClickListener { view: View ->
val intent = Intent(this, TimelapseSetupActivity::class.java)
startActivity(intent)
if (mConnectedThread != null) { //First check to make sure thread created
mConnectedThread!!.write('r')
}
}
backButton.setOnClickListener { view: View ->
points=0
updatePoints()
}
leftButton.setOnTouchListener(OnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
if (mConnectedThread != null) { //First check to make sure thread created
mConnectedThread!!.write('a')
}
} else if (event.action == MotionEvent.ACTION_UP) {
if (mConnectedThread != null) { //First check to make sure thread created
mConnectedThread!!.write('1')
}
}
true
})
rightButton.setOnTouchListener(OnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
if (mConnectedThread != null) { //First check to make sure thread created
mConnectedThread!!.write('9')
}
} else if (event.action == MotionEvent.ACTION_UP) {
if (mConnectedThread != null) { //First check to make sure thread created
mConnectedThread!!.write('1')
}
}
true
})
}
override fun onJoystickMoved(xPercent: Float, yPercent: Float, id: Int) {
Log.d("Joystick", "X percent: $xPercent Y percent: $yPercent")
if (mConnectedThread != null) { //First check to make sure thread created
if (xPercent > 0.1 && yPercent >0.1) mConnectedThread!!.write('1') //Pan Right & Tilt Up
else if (xPercent > 0.1 && yPercent< -0.1) mConnectedThread!!.write('2') //Pan Right & Tilt Down
else if (xPercent < -0.1 && yPercent > 0.1) mConnectedThread!!.write('3') //Pan Left & Tilt Up
else if (xPercent < -0.1 && yPercent < -0.1) mConnectedThread!!.write('4') //Pan Left & Tilt Down
else if (xPercent > 0.1) mConnectedThread!!.write('5') //Pan Right
else if (xPercent < -0.1) mConnectedThread!!.write('6') //Pan Left
else if (yPercent > 0.1) mConnectedThread!!.write('7') //Tilt Up
else if (yPercent < -0.1) mConnectedThread!!.write('8') //Tilt Down
else mConnectedThread!!.write('9')
}
}
}
private fun updatePoints(){
if(points ==1){
point1Button.setBackgroundColor(Color.GREEN)
}else if (points ==2){
point2Button.setBackgroundColor(Color.GREEN)
}else if (points >=3){
point3Button.setBackgroundColor(Color.GREEN)
}else{
point1Button.setBackgroundColor(Color.BLUE)
point2Button.setBackgroundColor(Color.BLUE)
point3Button.setBackgroundColor(Color.BLUE)
}
}
And here's my arduino code
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <SPI.h>
#include <Wire.h>
// -----------------------------------BLUETOOTH-----------------------------------
#include <SoftwareSerial.h> // use the software uart
SoftwareSerial bluetooth(0 , 1); // RX, TX
// -----------------------------------MENU-----------------------------------
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
//#include <Adafruit_PCD8544.h>
#include <ClickEncoder.h>
#include <TimerOne.h>
int contrast = 60;
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
int menuitem = 1;
int frame = 1;
int page = 0;
int mainMenuItem = 1;
int subMenuItem1 = 1;
int subMenuItem2 = 1;
int subMenuItem3 = 1;
int subMenuItem4 = 1;
String menuItem1 = "Setup";
String menuItem2 = "Free Control";
String menuItem3 = "Saved";
String menuItem4 = "Settings";
String setupItem1 = "Timelapse";
String setupItem2 = "Video";
String setupItem3 = "Back";
boolean up = false;
boolean down = false;
boolean middle = false;
bool sliderLengthSet = false;
// ------------------------------------------------------------------------------------
#define JoyX A0
#define JoyY A1
#define JoySwitch 10 // Joystick switch connected
// Rotary Encoder
#define CLK 8
#define DT 9
#define SW 12
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir = "";
unsigned long lastButtonPress = 0;
ClickEncoder *encoder;
int16_t last, value;
//Opto Trigger
#define opto 13
//limitSwitch
#define limitSwitch 11
AccelStepper tiltStepper(1, 2, 3);
AccelStepper panStepper(1, 4, 5);
AccelStepper sliderStepper(1, 6, 7);
MultiStepper StepperControl;
int JoyXPos = 0;
int JoyYPos = 0;
int tiltSpeed = 60;
int sliderSpeed = 1500;
int panSpeed = 10;
int inOutSpeed = 0;
int panInPoint = 0;
int tiltInPoint = 0;
int sliderInPoint = 0;
int panOutPoint = 0;
int tiltOutPoint = 0;
int sliderOutPoint = 0;
int sliderLength = 43; //in cm (725steps = 1cm)
int sliderLengthInSteps = (sliderLength * 725) - 100; //725steps = 1cm && 100 steps as safety
long gotoposition[3]; // An array to store the In or Out position for each stepper motor
//Rotary Encoder
int clickCount = 0;
bool rotaryEncoderMenuState = true; //true when in Menu mode, false when in slider mode
//Timer
long duration = 3000; //ms
//Intervalometer
int shotDuration = 100; //in ms
int interval = 3000; //in ms
int numberOfShots = 0;
char lastReading;
char bt ;
// ------------------------------------------------------------------ SETUP -------------------------------------------------------------------
void setup() {
//Bluetooth
bluetooth.begin(9600); // start the bluetooth uart at 9600 which is its default
//delay(3000); // wait for settings to take affect.
//Set initial speed values for the steppers
tiltStepper.setMaxSpeed(6000);
tiltStepper.setSpeed(0);
tiltStepper.setAcceleration(10);
panStepper.setMaxSpeed(6000);
panStepper.setSpeed(0);
panStepper.setAcceleration(5);
sliderStepper.setMaxSpeed(6000);
sliderStepper.setSpeed(0);
sliderStepper.setAcceleration(10);
StepperControl.addStepper(panStepper);
StepperControl.addStepper(tiltStepper);
StepperControl.addStepper(sliderStepper);
//limitSwitch
pinMode(limitSwitch, INPUT_PULLUP);
//Opto Trigger
pinMode(opto, OUTPUT);
// //Go to Home
// while (digitalRead(limitSwitch) == 0) {
// sliderStepper.setSpeed(500);
// sliderStepper.runSpeed();
// sliderStepper.setCurrentPosition(0); // When limit switch pressed set position to 0 steps
// }
// delay(20);
// // Move 200 steps back from the limit switch
// while (sliderStepper.currentPosition() != -500) {
// sliderStepper.setSpeed(-1500);
// sliderStepper.run();
// }
}
// ------------------------------------------------------------------ LOOP -------------------------------------------------------------------
void loop() {
//
// if (digitalRead(limitSwitch) != 0 || sliderStepper.currentPosition() < sliderLengthInSteps + 3000) {
// sliderStepper.setSpeed(1500);
// sliderStepper.run();
// }
if (bluetooth.available()) {
bt = bluetooth.read();
}
int inOutSpeed = 500; //steps per second
// -----------------------------------BLUETOOTH-----------------------------------
lastReading = bluetooth.read();
// while (lastReading == bluetooth.read()) {
// lastReading = bluetooth.read();
switch (bt) {
case '1':
sliderStepper.setSpeed(0);
tiltStepper.setSpeed(0);
panStepper.setSpeed(0);
break;
case '2':
panStepper.setSpeed(500);
bluetooth.print("Pan Right");
break;
case '3':
panStepper.setSpeed(-500);
bluetooth.print("Pan Left");
break;
case '4':
tiltStepper.setSpeed(-500);
bluetooth.print("Tilt Down");
break;
case '5':
tiltStepper.setSpeed(500);
bluetooth.print("Tilt Up");
break;
case '6':
//sliderStepper.setSpeed(500);
bluetooth.print("Slider Right");
break;
case '7':
//sliderStepper.setSpeed(-500);
bluetooth.print("Slider Left");
break;
case '9':
sliderStepper.setSpeed(500);
break;
case 'a':
sliderStepper.setSpeed(-500);
break;
case 'i':
panInPoint = panStepper.currentPosition();
tiltInPoint = tiltStepper.currentPosition();
sliderInPoint = sliderStepper.currentPosition();
break;
case 'o':
panOutPoint = panStepper.currentPosition();
tiltOutPoint = tiltStepper.currentPosition();
sliderOutPoint = sliderStepper.currentPosition();
gotoposition[0] = panInPoint;
gotoposition[1] = tiltInPoint;
gotoposition[2] = sliderInPoint;
//inOutSpeed = findSpeed();
panStepper.setMaxSpeed(500);
tiltStepper.setMaxSpeed(300);
sliderStepper.setMaxSpeed(500);
StepperControl.moveTo(gotoposition); // Calculates the required speed for all motors
while (panStepper.distanceToGo() != 0 || tiltStepper.distanceToGo() != 0 || sliderStepper.distanceToGo() != 0) {
StepperControl.run(); // Blocks until all are in position
}
delay(200);
bluetooth.println("o called");
break;
case'r':
bluetooth.println("r called");
gotoposition[0] = panOutPoint;
gotoposition[1] = tiltOutPoint;
gotoposition[2] = sliderOutPoint;
inOutSpeed = findSpeed();
bluetooth.println(inOutSpeed);
panStepper.setMaxSpeed(inOutSpeed);
tiltStepper.setMaxSpeed(inOutSpeed);
sliderStepper.setMaxSpeed(inOutSpeed);
StepperControl.moveTo(gotoposition); // Calculates the required speed for all motors
//StepperControl.runSpeedToPosition(); // Blocks until all are in position
long timePassed = millis();
long lastTrigger = millis();
while (panStepper.distanceToGo() != 0 || tiltStepper.distanceToGo() != 0 || sliderStepper.distanceToGo() != 0) {
StepperControl.run();
if ((millis() - lastTrigger) / 1000 == interval / 1000) {
Serial.println(lastTrigger);
digitalWrite(opto, HIGH);
delay(shotDuration); // wait for a shutter speed
digitalWrite(opto, LOW);
//delay(interval+duration);
Serial.println("triggered");
lastTrigger = millis();
}
}
break;
}
sliderStepper.runSpeed();
tiltStepper.runSpeed();
panStepper.runSpeed();
}
int findSpeed() {
numberOfShots = duration / (interval + shotDuration);
if (abs(panInPoint - panOutPoint) > abs(tiltInPoint - tiltOutPoint) && abs(panInPoint - panOutPoint) > abs(sliderInPoint - sliderOutPoint)) {
return (abs(panInPoint - panOutPoint) / ((duration - (shotDuration * numberOfShots)) / 1000));
} else if (abs(tiltInPoint - tiltOutPoint) > abs(panInPoint - panOutPoint) && abs(tiltInPoint - tiltOutPoint) > abs(sliderInPoint - sliderOutPoint)) {
return (abs(tiltInPoint - tiltOutPoint) / ((duration - (shotDuration * numberOfShots)) / 1000));
} else {
return (abs(sliderInPoint - sliderOutPoint) / ((duration - (shotDuration * numberOfShots)) / 1000));
}
}
//----------------------------------------------------- DRAW MENU -----------------------------------------------------
void drawMenu()
{
//Setup->Timelapse->Next
panInPoint = panStepper.currentPosition();
tiltInPoint = tiltStepper.currentPosition();
sliderInPoint = sliderStepper.currentPosition();
//Save Out Point
int inOutSpeed = 0;
panOutPoint = panStepper.currentPosition();
tiltOutPoint = tiltStepper.currentPosition();
sliderOutPoint = sliderStepper.currentPosition();
Serial.println("out");
Serial.println(panOutPoint);
Serial.println(tiltOutPoint);
Serial.println(sliderOutPoint);
//go to Start Point
gotoposition[0] = panInPoint;
gotoposition[1] = tiltInPoint;
gotoposition[2] = sliderInPoint;
Serial.println("in");
Serial.println(gotoposition[0]);
Serial.println(gotoposition[1]);
Serial.println(gotoposition[2]);
//inOutSpeed = findSpeed();
panStepper.setMaxSpeed(500);
tiltStepper.setMaxSpeed(300);
sliderStepper.setMaxSpeed(1000);
StepperControl.moveTo(gotoposition); // Calculates the required speed for all motors
StepperControl.runSpeedToPosition(); // Blocks until all are in position
delay(200);
//Setup->Timelapse->Next->Next-> Start
// Execute Move
gotoposition[0] = panOutPoint;
gotoposition[1] = tiltOutPoint;
gotoposition[2] = sliderOutPoint;
inOutSpeed = findSpeed();
panStepper.setMaxSpeed(inOutSpeed);
tiltStepper.setMaxSpeed(inOutSpeed);
sliderStepper.setMaxSpeed(inOutSpeed);
StepperControl.moveTo(gotoposition); // Calculates the required speed for all motors
//StepperControl.runSpeedToPosition(); // Blocks until all are in position
long timePassed = millis();
long lastTrigger = millis();
while (panStepper.distanceToGo() != 0 || tiltStepper.distanceToGo() != 0 || sliderStepper.distanceToGo() != 0) {
StepperControl.run();
if ((millis() - lastTrigger) / 1000 == interval / 1000) {
Serial.println(lastTrigger);
digitalWrite(opto, HIGH);
delay(shotDuration); // wait for a shutter speed
digitalWrite(opto, LOW);
//delay(interval+duration);
Serial.println("triggered");
lastTrigger = millis();
}
}
}
I'm receiving bluetooth data to my Arduino and the motors are turning, it's just not very accurate and misses some button presses.
Please could you help me! :)

Masked EditText with format (XXX) XXX-XXXX ext.XXXXXX in android?

How can I mask EditText with below format in android ?
(XXX) XXX-XXXX ext.XXXXXX i.e (654) 321-5846 ext.654321
Used below Custom Edit Text class
package com.test.PhoneNumberFormatter;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import com.test.R;
import static android.content.ContentValues.TAG;
public class MaskedEditText extends AppCompatEditText implements TextWatcher {
public static final String SPACE = " ";
private String mask;
private char charRepresentation;
private boolean keepHint;
private int[] rawToMask;
private RawText rawText;
private boolean editingBefore;
private boolean editingOnChanged;
private boolean editingAfter;
private int[] maskToRaw;
private int selection;
private boolean initialized;
private boolean ignore;
protected int maxRawLength;
private int lastValidMaskPosition;
private boolean selectionChanged;
private OnFocusChangeListener focusChangeListener;
private String allowedChars;
private String deniedChars;
public MaskedEditText(Context context) {
super(context);
init();
}
public MaskedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.MaskedEditText);
mask = attributes.getString(R.styleable.MaskedEditText_mask);
allowedChars = attributes.getString(R.styleable.MaskedEditText_allowed_chars);
deniedChars = attributes.getString(R.styleable.MaskedEditText_denied_chars);
String representation = attributes.getString(R.styleable.MaskedEditText_char_representation);
if (representation == null) {
charRepresentation = '#';
} else {
charRepresentation = representation.charAt(0);
}
keepHint = attributes.getBoolean(R.styleable.MaskedEditText_keep_hint, false);
cleanUp();
// Ignoring enter key presses
setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
switch (actionId) {
// case EditorInfo.IME_ACTION_NEXT:
// fixing actionNext
// return false;
default:
return true;
}
}
});
attributes.recycle();
}
#Override
public Parcelable onSaveInstanceState() {
final Parcelable superParcellable = super.onSaveInstanceState();
final Bundle state = new Bundle();
state.putParcelable("super", superParcellable);
state.putString("text", getRawText());
state.putBoolean("keepHint", isKeepHint());
return state;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
Bundle bundle = (Bundle) state;
keepHint = bundle.getBoolean("keepHint", false);
super.onRestoreInstanceState(((Bundle) state).getParcelable("super"));
final String text = bundle.getString("text");
setText(text);
Log.d(TAG, "onRestoreInstanceState: " + text);
}
#Override
public void setText(CharSequence text, BufferType type) {
// if (text == null || text.equals("")) return;
super.setText(text, type);
}
/**
* #param listener - its onFocusChange() method will be called before performing MaskedEditText operations,
* related to this event.
*/
#Override
public void setOnFocusChangeListener(OnFocusChangeListener listener) {
focusChangeListener = listener;
}
private void cleanUp() {
initialized = false;
generatePositionArrays();
rawText = new RawText();
selection = rawToMask[0];
editingBefore = true;
editingOnChanged = true;
editingAfter = true;
if (hasHint() && rawText.length() == 0) {
this.setText(makeMaskedTextWithHint());
} else {
this.setText(makeMaskedText());
}
editingBefore = false;
editingOnChanged = false;
editingAfter = false;
maxRawLength = maskToRaw[previousValidPosition(mask.length() - 1)] + 1;
lastValidMaskPosition = findLastValidMaskPosition();
initialized = true;
super.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (focusChangeListener != null) {
focusChangeListener.onFocusChange(v, hasFocus);
}
if (hasFocus()) {
selectionChanged = false;
MaskedEditText.this.setSelection(lastValidPosition());
}
}
});
}
private int findLastValidMaskPosition() {
for (int i = maskToRaw.length - 1; i >= 0; i--) {
if (maskToRaw[i] != -1) return i;
}
throw new RuntimeException("Mask must contain at least one representation char");
}
private boolean hasHint() {
return getHint() != null;
}
public MaskedEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public void setMask(String mask) {
this.mask = mask;
cleanUp();
}
public String getMask() {
return this.mask;
}
public String getRawText() {
return this.rawText.getText();
}
public void setCharRepresentation(char charRepresentation) {
this.charRepresentation = charRepresentation;
cleanUp();
}
public char getCharRepresentation() {
return this.charRepresentation;
}
/**
* Generates positions for values characters. For instance:
* Input data: mask = "+7(###)###-##-##
* After method execution:
* rawToMask = [3, 4, 5, 6, 8, 9, 11, 12, 14, 15]
* maskToRaw = [-1, -1, -1, 0, 1, 2, -1, 3, 4, 5, -1, 6, 7, -1, 8, 9]
* charsInMask = "+7()- " (and space, yes)
*/
private void generatePositionArrays() {
int[] aux = new int[mask.length()];
maskToRaw = new int[mask.length()];
String charsInMaskAux = "";
int charIndex = 0;
for (int i = 0; i < mask.length(); i++) {
char currentChar = mask.charAt(i);
if (currentChar == charRepresentation) {
aux[charIndex] = i;
maskToRaw[i] = charIndex++;
} else {
String charAsString = Character.toString(currentChar);
if (!charsInMaskAux.contains(charAsString)) {
charsInMaskAux = charsInMaskAux.concat(charAsString);
}
maskToRaw[i] = -1;
}
}
if (charsInMaskAux.indexOf(' ') < 0) {
charsInMaskAux = charsInMaskAux + SPACE;
}
char[] charsInMask = charsInMaskAux.toCharArray();
rawToMask = new int[charIndex];
for (int i = 0; i < charIndex; i++) {
rawToMask[i] = aux[i];
}
}
private void init() {
addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
if (!editingBefore) {
editingBefore = true;
if (start > lastValidMaskPosition) {
ignore = true;
}
int rangeStart = start;
if (after == 0) {
rangeStart = erasingStart(start);
}
Range range = calculateRange(rangeStart, start + count);
if (range.getStart() != -1) {
rawText.subtractFromString(range);
}
if (count > 0) {
selection = previousValidPosition(start);
}
}
}
private int erasingStart(int start) {
while (start > 0 && maskToRaw[start] == -1) {
start--;
}
return start;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!editingOnChanged && editingBefore) {
editingOnChanged = true;
if (ignore) {
return;
}
if (count > 0) {
int startingPosition = maskToRaw[nextValidPosition(start)];
String addedString = s.subSequence(start, start + count).toString();
count = rawText.addToString(clear(addedString), startingPosition, maxRawLength);
if (initialized) {
int currentPosition;
if (startingPosition + count < rawToMask.length)
currentPosition = rawToMask[startingPosition + count];
else
currentPosition = lastValidMaskPosition + 1;
selection = nextValidPosition(currentPosition);
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
if (!editingAfter && editingBefore && editingOnChanged) {
editingAfter = true;
if (hasHint() && (keepHint || rawText.length() == 0)) {
setText(makeMaskedTextWithHint());
} else {
setText(makeMaskedText());
}
selectionChanged = false;
setSelection(selection);
editingBefore = false;
editingOnChanged = false;
editingAfter = false;
ignore = false;
}
}
public boolean isKeepHint() {
return keepHint;
}
public void setKeepHint(boolean keepHint) {
this.keepHint = keepHint;
setText(getRawText());
}
#Override
protected void onSelectionChanged(int selStart, int selEnd) {
// On Android 4+ this method is being called more than 1 time if there is a hint in the EditText, what moves the cursor to left
// Using the boolean var selectionChanged to limit to one execution
if (initialized) {
if (!selectionChanged) {
selStart = fixSelection(selStart);
selEnd = fixSelection(selEnd);
// exactly in this order. If getText.length() == 0 then selStart will be -1
if (selStart > getText().length()) selStart = getText().length();
if (selStart < 0) selStart = 0;
// exactly in this order. If getText.length() == 0 then selEnd will be -1
if (selEnd > getText().length()) selEnd = getText().length();
if (selEnd < 0) selEnd = 0;
setSelection(selStart, selEnd);
selectionChanged = true;
} else {
//check to see if the current selection is outside the already entered text
if (selStart > rawText.length() - 1) {
final int start = fixSelection(selStart);
final int end = fixSelection(selEnd);
if (start >= 0 && end < getText().length()) {
setSelection(start, end);
}
}
}
}
super.onSelectionChanged(selStart, selEnd);
}
private int fixSelection(int selection) {
if (selection > lastValidPosition()) {
return lastValidPosition();
} else {
return nextValidPosition(selection);
}
}
private int nextValidPosition(int currentPosition) {
while (currentPosition < lastValidMaskPosition && maskToRaw[currentPosition] == -1) {
currentPosition++;
}
if (currentPosition > lastValidMaskPosition) return lastValidMaskPosition + 1;
return currentPosition;
}
private int previousValidPosition(int currentPosition) {
while (currentPosition >= 0 && maskToRaw[currentPosition] == -1) {
currentPosition--;
if (currentPosition < 0) {
return nextValidPosition(0);
}
}
return currentPosition;
}
private int lastValidPosition() {
if (rawText.length() == maxRawLength) {
return rawToMask[rawText.length() - 1] + 1;
}
return nextValidPosition(rawToMask[rawText.length()]);
}
private String makeMaskedText() {
int maskedTextLength;
if (rawText.length() < rawToMask.length) {
maskedTextLength = rawToMask[rawText.length()];
} else {
maskedTextLength = mask.length();
}
char[] maskedText = new char[maskedTextLength]; //mask.replace(charRepresentation, ' ').toCharArray();
for (int i = 0; i < maskedText.length; i++) {
int rawIndex = maskToRaw[i];
if (rawIndex == -1) {
maskedText[i] = mask.charAt(i);
} else {
maskedText[i] = rawText.charAt(rawIndex);
}
}
return new String(maskedText);
}
private CharSequence makeMaskedTextWithHint() {
SpannableStringBuilder ssb = new SpannableStringBuilder();
int mtrv;
int maskFirstChunkEnd = rawToMask[0];
for (int i = 0; i < mask.length(); i++) {
mtrv = maskToRaw[i];
if (mtrv != -1) {
if (mtrv < rawText.length()) {
ssb.append(rawText.charAt(mtrv));
} else {
ssb.append(getHint().charAt(maskToRaw[i]));
}
} else {
ssb.append(mask.charAt(i));
}
if ((keepHint && rawText.length() < rawToMask.length && i >= rawToMask[rawText.length()])
|| (!keepHint && i >= maskFirstChunkEnd)) {
ssb.setSpan(new ForegroundColorSpan(getCurrentHintTextColor()), i, i + 1, 0);
}
}
return ssb;
}
private Range calculateRange(int start, int end) {
Range range = new Range();
for (int i = start; i <= end && i < mask.length(); i++) {
if (maskToRaw[i] != -1) {
if (range.getStart() == -1) {
range.setStart(maskToRaw[i]);
}
range.setEnd(maskToRaw[i]);
}
}
if (end == mask.length()) {
range.setEnd(rawText.length());
}
if (range.getStart() == range.getEnd() && start < end) {
int newStart = previousValidPosition(range.getStart() - 1);
if (newStart < range.getStart()) {
range.setStart(newStart);
}
}
return range;
}
private String clear(String string) {
if (deniedChars != null) {
for (char c : deniedChars.toCharArray()) {
string = string.replace(Character.toString(c), "");
}
}
if (allowedChars != null) {
StringBuilder builder = new StringBuilder(string.length());
for (char c : string.toCharArray()) {
if (allowedChars.contains(String.valueOf(c))) {
builder.append(c);
}
}
string = builder.toString();
}
return string;
}
}
In activity_main.xml
<com.test.PhoneNumberFormatter.MaskedEditText
android:id="#+id/phone_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:hint="#string/phone_number"
android:imeOptions="actionNext"
android:inputType="textPhonetic"
android:paddingBottom="#dimen/_3sdp"
android:paddingTop="#dimen/_8sdp"
android:textColorHint="#color/grey_color"
android:textSize="#dimen/_12sdp"
mask:allowed_chars="1234567890ext."
mask:keep_hint="false"
mask:mask="(###)###-#### ext.######" />
Thanks.
For format Edit-text, below things can be helpful to you.
**Step 1** : Add following line in your build.gradle file
implementation 'com.github.pinball83:masked-edittext:1.0.4'
**Step 2 :** by xml :
<com.github.pinball83.maskededittext.MaskedEditText
android:id="#+id/masked_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
app:mask="8 (***) *** **-**"
app:notMaskedSymbol="*"
app:maskIcon="#drawable/abc_ic_clear_mtrl_alpha"
app:maskIconColor="#color/colorPrimary"
/>
or by java file :
MaskedEditText maskedEditText = new MaskedEditText.Builder(context)
.mask("8 (***) *** **-**")
.notMaskedSymbol("*")
.icon(R.drawable.ic_account_circle)
.iconCallback(unmaskedText -> { //Icon click callback handler })
.build();
MaskedEditText editText = new MaskedEditText.Builder(context)
.mask("8 (***) *** **-**")
.notMaskedSymbol("*")
.build();; //set mask to "8 (***) *** **-**" and not masked symbol to "*"
Text setup and formatting
MaskedEditText editText = new MaskedEditText..Builder(context)
.mask("8 (***) *** **-**")
.notMaskedSymbol("*")
.format("[1][2][3] [4][5][6]-[7][8]-[10][9]")//set format of returned data input into MaskedEditText
.build();
editText.setMaskedText("5551235567");
for more details use following url :
https://github.com/pinball83/Masked-Edittext
Enjoy :)
Step 1 : Create editText
<EditText
android:id="#+id/masked_edit_text"
android:layout_width="yourSize"
android:layout_height="yourSize"
android:inputType="textPassword"/>
Step2:
public class CustomTransformation extends PasswordTransformationMethod {
#Override
public CharSequence getTransformation(CharSequence source, View view) {
return new TransformedSequence(source);
}
private class TransformedSequence implements CharSequence {
private CharSequence sequence;
public TransformedSequence(CharSequence source) {
sequence = source; // Store char sequence
}
public char charAt(int index) {
return 'X'; // Replace with what you want.
}
public int length() {
return sequence.length(); // return the length
}
public CharSequence subSequence(int start, int end) {
return sequence.subSequence(start, end); //return sequence
}
}
Step 3: apply the transformation
EditText edittext = findViewById(R.id.masked_edit_text);
edittext.setTransformationMethod(new CustomTransformation());
https://github.com/mukeshsolanki/country-picker-android
try this library .
this will automatically mask your edittext with selected country number .

Open a actvity when a if statement comes true

Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);

How can I save my current imageview when onClick?

How can I save my current ImageView when I press onClick?
Im currently having the problem that the image that is next in line is being saved instead of the current actual image..
My Code for saving onLike
public class MainActivity extends Activity implements SwipeView.OnCardSwipedListener {
// Declaring variables
private final static int CARDS_MAX_ELEMENTS = 5;
private FrameLayout contentLayout;
private SwipeView mSwipeView;
private View addCardc41;
private Firebase mRef;
public ImageView imageLogo;
public ImageView imageview;
private static final String TAG = "MyActivity";
// Creating array of meals, getting them from the drawable folder
private int[] meals = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f,
R.drawable.g,
R.drawable.h,
R.drawable.i,
R.drawable.j
};
// Declaring a counter for the next method
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view_demo);
contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
imageLogo = (ImageView) findViewById(R.id.imageView3);
imageview = (ImageView) findViewById(R.id.imageView);
// Add the swipe view
mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
this);
contentLayout.addView(mSwipeView);
// Adding the cards initially with the maximum limits of cards.
for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
addCard(i);
}
}
/**
* On clicked view.
*
* #param clickedView
* the clicked view
*/
public void onClickedView(View clickedView) {
switch (clickedView.getId()) {
case R.id.imgDisLike: {
mSwipeView.dislikeCard();
break;
}
case R.id.imgLike: {
mSwipeView.likeCard();
break;
}
}
}
#Override
public void onLikes() {
imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onDisLikes() {
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onSingleTap() {
}
/**
* Adds the card to the swipe.
*/
private void addCard(int position) {
final View cardView = LayoutInflater.from(this).inflate(
R.layout.item_swipe_view, null);
final ImageView imgMeal = (ImageView) cardView
.findViewById(R.id.imgMeals);
imgMeal.setImageResource(meals[count]);
count++;
if (count == meals.length) {
count = 0;
}
// Add a card to the swipe view..
mSwipeView.addCard(cardView, position);
// Create OnClickListener for the CookBookActivity
// Declare Button for the Cookbook
Button btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CookbookActivity.class));
}
});
// Check Authentication
mRef = new Firebase(Constants.FIREBASE_URL);
if (mRef.getAuth() == null) {
loadLoginView();
}
}
private void loadLoginView() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
The Library that i'm using for the swiping
//
// credits to IntelliJ IDEA
// (powered by Fernflower decompiler)
package com.rk.lib.view;
import android.content.Context;
import android.os.Handler;
import android.os.Build.VERSION;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
public class SwipeView extends FrameLayout {
private View mFocusedView;
private View mFocusedViewLike;
private View mFocusedViewNope;
private int mFocusedViewWidth;
private float mPreviousAlpha = 0.0F;
private Integer mLikeResource = Integer.valueOf(0);
private Integer mNopeResource = Integer.valueOf(0);
private static final int MAX_ELEMENTS = 3;
private static final long DELAY_SCROLL_RUNNABLE = 1L;
private static final int SCROLL_LENGTH = 5;
private int mScrolledPixelsX;
private int mScrolledPixelsY;
private int mNeedToScrollX;
private int mNeedToScrollY;
private int mTotalScrolledX;
private int mTotalScrolledY;
private int mScrollLengthX = 5;
private int mScrollLengthY = 5;
private boolean enableTouchSwipe = true;
private Context mContext;
private SwipeView.ScrollMode mScrollModeX;
private SwipeView.ScrollMode mScrollModeY;
private SwipeView.ScrollDirection mScrollDirection;
private int[] paddingX;
private int[] paddingYTop;
private int[] paddingYBottom;
private SwipeView.OnCardSwipedListener mOnCardSwipedListener;
private Handler mScrollHandler;
private Runnable mScrollRunnable;
private final SimpleOnGestureListener simpleOnGestureListener;
public SwipeView(Context context, Integer likeResource, Integer nopeResource, SwipeView.OnCardSwipedListener cardSwipeListener) {
super(context);
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
this.paddingX = new int[]{0, 10, 20};
this.paddingYTop = new int[]{0, 10, 20};
this.paddingYBottom = new int[]{20, 10, 0};
this.mScrollHandler = new Handler();
this.mScrollRunnable = new Runnable() {
public void run() {
boolean scrollX;
boolean scrollY;
int scrollX1;
int scrollY1;
if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.OUT) {
if(SwipeView.this.mNeedToScrollX <= 0 && SwipeView.this.mNeedToScrollY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.removeView(SwipeView.this.mFocusedView);
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
SwipeView.this.mOnCardSwipedListener.onLikes();
} else if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.RIGHT) {
SwipeView.this.mOnCardSwipedListener.onDisLikes();
}
SwipeView.this.alignCardsPadding();
} else {
if(SwipeView.this.mNeedToScrollX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mNeedToScrollX;
SwipeView.this.mNeedToScrollX = 0;
} else {
SwipeView.this.mNeedToScrollX = SwipeView.this.mNeedToScrollX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mNeedToScrollY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mNeedToScrollY;
SwipeView.this.mNeedToScrollY = 0;
} else {
SwipeView.this.mNeedToScrollY = SwipeView.this.mNeedToScrollY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = -SwipeView.this.mScrollLengthX;
} else {
scrollX1 = SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
} else if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.IN) {
if(SwipeView.this.mTotalScrolledX <= 0 && SwipeView.this.mTotalScrolledY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.mScrollDirection = SwipeView.ScrollDirection.NONE;
} else {
if(SwipeView.this.mTotalScrolledX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mTotalScrolledX;
SwipeView.this.mTotalScrolledX = 0;
} else {
SwipeView.this.mTotalScrolledX = SwipeView.this.mTotalScrolledX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mTotalScrolledY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mTotalScrolledY;
SwipeView.this.mTotalScrolledY = 0;
} else {
SwipeView.this.mTotalScrolledY = SwipeView.this.mTotalScrolledY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = SwipeView.this.mScrollLengthX;
} else {
scrollX1 = -SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
}
}
};
this.simpleOnGestureListener = new SimpleOnGestureListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
SwipeView.this.mOnCardSwipedListener.onSingleTap();
return super.onSingleTapConfirmed(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(SwipeView.this.mFocusedView != null) {
SwipeView.this.mScrolledPixelsX = SwipeView.this.mScrolledPixelsX + (int)distanceX;
SwipeView.this.mScrolledPixelsY = SwipeView.this.mScrolledPixelsY + (int)distanceY;
SwipeView.this.mFocusedView.scrollBy((int)distanceX, (int)distanceY);
float alpha = (float)SwipeView.this.mScrolledPixelsX / (float)SwipeView.this.mFocusedViewWidth;
if(alpha > 0.0F) {
SwipeView.this.mFocusedViewNope.setVisibility(0);
SwipeView.this.mFocusedViewLike.setVisibility(8);
SwipeView.setAlpha(SwipeView.this.mFocusedViewNope, SwipeView.this.mPreviousAlpha, alpha);
SwipeView.this.mPreviousAlpha = alpha;
} else {
SwipeView.this.mFocusedViewNope.setVisibility(8);
SwipeView.this.mFocusedViewLike.setVisibility(0);
SwipeView.setAlpha(SwipeView.this.mFocusedViewLike, SwipeView.this.mPreviousAlpha, -alpha);
SwipeView.this.mPreviousAlpha = -alpha;
}
}
return true;
}
};
this.mContext = context;
this.mLikeResource = likeResource;
this.mNopeResource = nopeResource;
this.mOnCardSwipedListener = cardSwipeListener;
float density = this.getResources().getDisplayMetrics().density;
for(int gestureDetector = 0; gestureDetector < this.paddingX.length; ++gestureDetector) {
this.paddingX[gestureDetector] = (int)((float)this.paddingX[gestureDetector] * density);
this.paddingYTop[gestureDetector] = (int)((float)this.paddingYTop[gestureDetector] * density);
this.paddingYBottom[gestureDetector] = (int)((float)this.paddingYBottom[gestureDetector] * density);
}
final GestureDetector var7 = new GestureDetector(this.mContext, this.simpleOnGestureListener);
this.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(SwipeView.this.getChildCount() > 0) {
if(SwipeView.this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return false;
} else if(!SwipeView.this.enableTouchSwipe) {
return false;
} else {
var7.onTouchEvent(event);
switch(event.getAction()) {
case 0:
if(SwipeView.this.getChildCount() > 0) {
SwipeView.this.mFocusedView = SwipeView.this.getChildAt(SwipeView.this.getChildCount() - 1);
SwipeView.this.mFocusedViewLike = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mLikeResource.intValue());
SwipeView.this.mFocusedViewNope = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mNopeResource.intValue());
SwipeView.this.mFocusedViewWidth = SwipeView.this.mFocusedView.getWidth();
SwipeView.this.mFocusedView.setPadding(SwipeView.this.paddingX[0], 0, SwipeView.this.paddingX[0], 0);
}
SwipeView.this.resetScrollingValues();
break;
case 1:
SwipeView.this.alignCardsPadding();
if(SwipeView.this.mScrolledPixelsX < 0) {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.LEFT;
SwipeView.this.mTotalScrolledX = -SwipeView.this.mScrolledPixelsX;
} else {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
SwipeView.this.mTotalScrolledX = SwipeView.this.mScrolledPixelsX;
}
if(SwipeView.this.mScrolledPixelsY < 0) {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.BOTTOM;
SwipeView.this.mTotalScrolledY = -SwipeView.this.mScrolledPixelsY;
} else {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.TOP;
SwipeView.this.mTotalScrolledY = SwipeView.this.mScrolledPixelsY;
}
SwipeView.this.detectSwipe();
}
return true;
}
} else {
return false;
}
}
});
}
public void addCard(View view, int position) {
if(this.getChildCount() <= 3 && position < 3) {
LinearLayout viewLayout = new LinearLayout(this.mContext);
viewLayout.setLayoutParams(new LayoutParams(-1, -1));
view.setLayoutParams(new LayoutParams(-1, -1));
viewLayout.addView(view);
viewLayout.setPadding(this.paddingX[position], this.paddingYTop[position], this.paddingX[position], this.paddingYBottom[position]);
this.addView(viewLayout, 0);
}
}
public void removeFocusedCard() {
this.removeView(this.mFocusedView);
this.alignCardsPadding();
}
private void alignCardsPadding() {
int i = 0;
for(int j = this.getChildCount() - 1; j >= 0; --j) {
this.getChildAt(j).setPadding(this.paddingX[i], this.paddingYTop[i], this.paddingX[i], this.paddingYBottom[i]);
++i;
}
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
}
private void resetScrollingValues() {
this.mPreviousAlpha = 0.0F;
this.mNeedToScrollX = 0;
this.mScrolledPixelsX = 0;
this.mTotalScrolledX = 0;
this.mNeedToScrollY = 0;
this.mScrolledPixelsY = 0;
this.mTotalScrolledY = 0;
this.mScrollLengthX = 5;
this.mScrollLengthY = 5;
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
}
public void resetFocuedView() {
if(this.getChildCount() > 0) {
View mFocusedView = this.getChildAt(this.getChildCount() - 1);
View mFocusedViewLike = mFocusedView.findViewById(this.mLikeResource.intValue());
View mFocusedViewNope = mFocusedView.findViewById(this.mNopeResource.intValue());
setAlpha(mFocusedViewLike, 0.0F, 0.0F);
setAlpha(mFocusedViewNope, 0.0F, 0.0F);
mFocusedView.scrollTo(0, 0);
}
}
private void detectSwipe() {
int imageHalf = this.mFocusedView.getWidth() / 2;
this.mNeedToScrollX = this.mFocusedView.getWidth() - this.mTotalScrolledX;
if(this.mScrollDirection == SwipeView.ScrollDirection.NONE) {
if(this.mNeedToScrollX < imageHalf) {
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
} else {
this.mScrollDirection = SwipeView.ScrollDirection.IN;
setAlpha(this.mFocusedViewLike, 0.0F, 0.0F);
setAlpha(this.mFocusedViewNope, 0.0F, 0.0F);
}
}
this.mScrollHandler.post(this.mScrollRunnable);
}
public void likeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.LEFT;
this.mFocusedViewLike.setVisibility(0);
setAlpha(this.mFocusedViewLike, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void dislikeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
this.mFocusedViewNope.setVisibility(0);
setAlpha(this.mFocusedViewNope, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void setTouchable(boolean touchable) {
this.enableTouchSwipe = touchable;
}
public static void setAlpha(View view, float fromAlpha, float toAlpha) {
if(VERSION.SDK_INT < 11) {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(0L);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
} else {
view.setAlpha(toAlpha);
}
}
public interface OnCardSwipedListener {
void onLikes();
void onDisLikes();
void onSingleTap();
}
private static enum ScrollDirection {
IN,
OUT,
NONE;
private ScrollDirection() {
}
}
private static enum ScrollMode {
LEFT,
RIGHT,
TOP,
BOTTOM,
NONE;
private ScrollMode() {
}
}
}
ATTEMPT #3
This is the code that i've tried but I keep getting the same result (read comment below what I have done:
FrameLayout view = (FrameLayout)findViewById(R.id.contentLayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
I believe the image you are trying to save is getting removed during the onSwipe due to the library code. I think you need to move your code to before the onLike is called.
You're also attempting to get a bitmap from the cache of the entire layout, rather than the wanted ImageView here:
bm=contentLayout.getDrawingCache();
You'll want to get your current card view as a View, then, from my understanding of your code, the ID of your actual ImageView containing the expected bitmap is R.id.imgMeals, so I the suggest replacing the line:
bm=contentLayout.getDrawingCache();
with the following:
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
Move all of the below code from where you have it, to where I have marked //HERE!! in the following part of your code (or better, move it to a new method and call the method here).
// If the imageview of like is clicked
case R.id.imgLike: {
// HERE!!
// The imageview in the contentlayout will be swiped to the right
mSwipeView.likeCard();
break;
}
This is the code to me moved including the change I mention above:
View cardView = mSwipeView.getChildAt(mSwipeView.getChildCount() - 1);
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
OutputStream fOut = null;
try {
// Save on my sd card
File root = new File(Environment.getExternalStorageDirectory()
// Making a folder name Food Inspiration
+ File.separator + "Food Inspiration" + File.separator);
root.mkdirs();
File sdImageMainDirectory = null;
// Loop for having a different name for every image
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
fOut = new FileOutputStream(sdImageMainDirectory);
// Updates the gallery of your phone with the folder and the "liked" images in it
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
// If something goes wrong
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
// Compresses the actual bitmap image
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}

gallery swiping app using array

please help guys,, here is my code for my simple gallery android app for external images
I made the loader is in array , and I made swiping action ,,
what I think I have to chose Wither removechild nor enter frame but I can't apply it
coz when publish, things is mixed up and swiping is not working well :(
could you please help me to fix it it's AS3 at Flash 5.5
var pictureArray:Array = new Array;
var loader1 = new Loader();
loader1.load(new URLRequest("1.jpg"));
pictureArray.push(loader1);
var loader2 = new Loader();
loader2.load(new URLRequest("2.jpg"));
pictureArray.push(loader2);
var loader3 = new Loader();
loader3.load(new URLRequest("3.jpg"));
pictureArray.push(loader3);
addChild(pictureArray[0]);
pictureArray[0].x = 0; pictureArray[0].y = 0;
var n:int = 0;
Multitouch.inputMode = MultitouchInputMode.GESTURE;
var currentGalleryItem:Number = 1;
var totalGalleryItems:Number = 3;
stage.addEventListener (TransformGestureEvent.GESTURE_SWIPE, fl_SwipeToGoToNextPreviousFrame);
function fl_SwipeToGoToNextPreviousFrame(event:TransformGestureEvent):void
{
if(event.offsetX == 1)
{
if(currentGalleryItem > 1){
currentGalleryItem--;
slideRight();
removeChild(pictureArray[n]);
n = n+1;
if (n>pictureArray.length - 1)
n=0;
addChild(pictureArray[n]);
pictureArray[n].x = 0; pictureArray[n].y = 0;
}
}
else if(event.offsetX == -1)
{
if(currentGalleryItem < totalGalleryItems){
currentGalleryItem++;
slideLeft();
removeChild(pictureArray[n]);
n = n-1;
if (n<0)
n=pictureArray.length - 1;
addChild(pictureArray[n]);
pictureArray[n].x = 0; pictureArray[n].y = 0;
}
}
}
var slideCounter:Number = 0;
function slideLeft(){
(pictureArray[n]).addEventListener("enterFrame", moveGalleryLeft);
}
function slideRight(){
(pictureArray[n]).addEventListener("enterFrame", moveGalleryRight);
}
function moveGalleryLeft(evt:Event){
(pictureArray[n]).x -= 48;
slideCounter++;
if(slideCounter == 5){
(pictureArray[n]).removeEventListener("enterFrame", moveGalleryLeft);
slideCounter = 0;
}
}
function moveGalleryRight(evt:Event){
(pictureArray[n]).x += 48;
slideCounter++;
if(slideCounter == 5){
(pictureArray[n]).removeEventListener("enterFrame", moveGalleryRight);
slideCounter = 0;
}
}
I would recommend load images on demand, for animation use some tweening engine(in my example It's TweenLite), and dispose previous frames, It's mobile device you should honour memory. Most of other comments in the code, I don't have ability to test in on the device, also It's not complete code, It's only carcass ;)
package {
import com.greensock.TweenLite;
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.TransformGestureEvent;
import flash.net.URLRequest;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class StackOverflow extends Sprite {
private var _loader:Loader;
private var _images:Array;
private var _position:int;
private var _currentFrame:Sprite;
public function StackOverflow() {
addEventListener(Event.ADDED_TO_STAGE, onAdded);
}
private function setup():void {
_loader = new Loader();
_images = ["1.jpg", "2.jpg", "3.jpg"];
_currentFrame = new Sprite();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadImage);
stage.addEventListener(TransformGestureEvent.GESTURE_SWIPE, onSwipe);
addChild(_currentFrame);
loadImageAtPosition(_position);
}
private function disposeFrame(frame:Sprite):void {
//You can cache loaded bitmaps, or dispose them
removeChild(frame);
var bitmap:Bitmap = frame.getChildAt(0) as Bitmap;
bitmap.bitmapData.dispose();
}
private function loadImageAtPosition(index:int):void {
//By using one loader for all tasks, you will have only last requested image
_loader.load(new URLRequest(_images[index]));
}
private function offsetScreenOn(direction:Number):void {
var offset:int;
var start:int;
if (direction > 0) {
//Direction to the right side
offset = stage.stageWidth;
} else {
//Direction to the left side
offset = -stage.stageWidth;
}
//Starting position for new frame
start = -offset;
//TweenLite is great for such task
if (_currentFrame != null) {
//Remove previous frame
TweenLite.to(_currentFrame, 0.8, {x: offset, onComplete: disposeFrame, onCompleteParams: [_currentFrame]});
}
//Initialise new frame, fill them, decor them...
_currentFrame = new Sprite();
if (_currentFrame != null) {
addChild(_currentFrame);
_currentFrame.x = start;
//Animate in new frame
TweenLite.to(_currentFrame, 0.8, {x: (start + offset)});
}
}
private function onLoadImage(e:Event):void {
if (_currentFrame != null) {
var image:Bitmap = _loader.content as Bitmap;
if (image != null) {
image.smoothing = true;
_currentFrame.addChild(image);
//Resize, displace image for your needs
//Add appear animation if you want
}
}
}
//If you want, you can postpone swipe, while in state of transition
private function onSwipe(e:TransformGestureEvent):void {
//Left to Right swipe
if (e.offsetX == 1) {
if (--_position < 0) {
_position = _images.length;
}
offsetScreenOn(e.offsetX);
loadImageAtPosition(_position);
}
//Right to Left swipe
if (e.offsetX == -1) {
if (++_position >= _images.length) {
_position = 0;
}
offsetScreenOn(e.offsetX);
loadImageAtPosition(_position);
}
}
private function onAdded(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, onAdded);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
Multitouch.inputMode = MultitouchInputMode.GESTURE;
setup();
}
}
}
check this out
simple android gallery
it a basic implementation of a gallery app, it makes use of the android media provider to actually get images in the device storage and provides an image slider by using a viewPager and a RecyclerView as indicator, I will outline the important parts here, you can use a RecyclerView and a Recycler Adapter to display your images
public class picture_Adapter extends RecyclerView.Adapter<PicHolder> {
private ArrayList<pictureFacer> pictureList;
private Context pictureContx;
private final itemClickListener picListerner;
/**
*
* #param pictureList ArrayList of pictureFacer objects
* #param pictureContx The Activities Context
* #param picListerner An interface for listening to clicks on the RecyclerView's items
*/
public picture_Adapter(ArrayList<pictureFacer> pictureList, Context pictureContx,itemClickListener picListerner) {
this.pictureList = pictureList;
this.pictureContx = pictureContx;
this.picListerner = picListerner;
}
#NonNull
#Override
public PicHolder onCreateViewHolder(#NonNull ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(container.getContext());
View cell = inflater.inflate(R.layout.pic_holder_item, container, false);
return new PicHolder(cell);
}
#Override
public void onBindViewHolder(#NonNull final PicHolder holder, final int position) {
final pictureFacer image = pictureList.get(position);
Glide.with(pictureContx)
.load(image.getPicturePath())
.apply(new RequestOptions().centerCrop())
.into(holder.picture);
setTransitionName(holder.picture, String.valueOf(position) + "_image");
holder.picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
picListerner.onPicClicked(holder,position, pictureList);
}
});
}
#Override
public int getItemCount() {
return pictureList.size();
}
}
the method below gets all the device images and load the info for each image in a imageFacer object which you can use to populate the recyclerview adapter
see the full post in the link above
public ArrayList<pictureFacer> getAllImagesByFolder(String path){
ArrayList<pictureFacer> images = new ArrayList<>();
Uri allVideosuri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaStore.Images.ImageColumns.DATA ,MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.SIZE};
Cursor cursor = ImageDisplay.this.getContentResolver().query( allVideosuri, projection, MediaStore.Images.Media.DATA + " like ? ", new String[] {"%"+path+"%"}, null);
try {
cursor.moveToFirst();
do{
pictureFacer pic = new pictureFacer();
pic.setPicturName(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)));
pic.setPicturePath(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)));
pic.setPictureSize(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)));
images.add(pic);
}while(cursor.moveToNext());
cursor.close();
ArrayList<pictureFacer> reSelection = new ArrayList<>();
for(int i = images.size()-1;i > -1;i--){
reSelection.add(images.get(i));
}
images = reSelection;
} catch (Exception e) {
e.printStackTrace();
}
return images;
}

Categories

Resources