SwipeGestureDetector change image from int [] to Imageview (Top & Bottom) - java

I need to take an image from an int Array and show then in Imageview when i swipe from bottom to top and top to bottom.
The GestureDetector works well but i want to take an image from an int [] and put then in Imageview when swipe.
Exemple :
int [] imageBank = new int[] {
R.drawable.image0,
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4, };
Swipe top to bottom,
take image 0 from [ ],
show in Imageview
Swipe top to bottom,
take image 1 from [ ],
show in Imageview
Swipe bottom to top,
take image 0 from [ ],
show in Imageview
Swipe bottom to top,
take image 4 from [ ],
show in Imageview
Complete MainActivity
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import driss.moodtracker.R;
import driss.moodtracker.component.SwipeGestureDetector;
public class MainActivity extends AppCompatActivity {
private SwipeGestureDetector gestureDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gestureDetector = new SwipeGestureDetector(this);
Button button_comment = (Button) findViewById(R.id.button1);
Button button_calendar = (Button) findViewById(R.id.button2);
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
public void onSwipe(SwipeGestureDetector.SwipeDirection direction) {
ImageView imagePic = (ImageView) findViewById(R.id.imageview);
ConstraintLayout currentLayout = (ConstraintLayout) findViewById(R.id.main_layout);
// ARRAY OF SMILEYS LIST
int [] arraySmileys = new int[] {
R.drawable.smiley_super_happy,
R.drawable.smiley_happy,
R.drawable.smiley_normal,
R.drawable.smiley_disappointed,
R.drawable.smiley_sad,
};
// HOW CAN I DO ?
String message = "";
switch (direction) {
case LEFT_TO_RIGHT:
message = "Left to right swipe";
break;
case RIGHT_TO_LEFT:
message = "Right to left swipe";
break;
case TOP_TO_BOTTOM:
imagePic.setImageResource(R.drawable.smiley_disappointed);
currentLayout.setBackgroundResource(R.color.faded_red);
message = "Top to bottom swipe";
break;
case BOTTOM_TO_TOP:
currentLayout.setBackgroundResource(R.color.light_sage);
imagePic.setImageResource(R.drawable.smiley_super_happy);
message = " Bottom to top swipe";
break;
}
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Thanks you for your help
A new student.

Define a 'counter' (integer variable) to store the index of your integer array. Now based on swipe detected, if user swipe from bottom to up increment the counter and set that index item's image to your imageview and vice versa for up to bottom.
Example code :
int counter = 0;
public void swipe() {
switch (direction) {
case LEFT_TO_RIGHT:
message = "Left to right swipe";
break;
case RIGHT_TO_LEFT:
message = "Right to left swipe";
break;
case TOP_TO_BOTTOM:
if(counter > 0) {
counter--;
imagePic.setImageResource(arraySmileys[counter]);
}
break;
case BOTTOM_TO_TOP:
if(counter < arraySmileys.length()) {
counter++;
imagePic.setImageResource(arraySmileys[counter]);
}
break;
}
}

It is better to use ViewPager or RecyclerView with ViewPager-like behavior instead of GestureDetector

Related

Android: switch case & random number code in the case

Android, java, studio 4.0.1
Trying to code by my own, I am facing an issue which I do not understand from the compiler statements.
Basically, when you click a radio button, a random number is generated in the textview field.
My problem is that the random code written in the case of the clicked radio button is not accepted by the compiler.
Here is the code:
package com.example.random;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
TextView MytextView = (TextView)findViewById(R.id.MytextView);
int random;
int random2;
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButton01:
if (checked)
// 0 or 1 code
random = getRandomNumber(0,1);
MytextView.setText(random.toString());
break;
case R.id.radioButton1to6:
if (checked)
// 1 to 6 code
random2 = getRandomNumber(1,6);
MytextView.setText(random2.toString());
break;
}
}
private int getRandomNumber(int min,int max) {
return (new Random()).nextInt((max - min) + 1) + min;
}
}
I presume that the 2 lines 'Int random;' are wrong, but the compiler seems to want to have them here.
I would have understood that the line 'random = getRandomNumber(0,1);' would have be sufficient in the case part of the code, but the compiler marks 'random' in red.
So far, the compiler says: 'error: int cannot be dereferenced in the MytextView.setText(random.toString());' of the //0 or 1 code part.
I would like to understand what I am missing here. Thanks in advance.
(Or asked simpler: how does one code a random function in a switch/case ?)
ok I found the solution. A possible working code is:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
TextView MytextView = (TextView)findViewById(R.id.MytextView);
final Random rnd = new Random();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButton01:
if (checked)
// 0 or 1 code
MytextView.setText(String.valueOf(rnd.nextInt(3-0) + 0));
break;
case R.id.radioButton1to6:
if (checked)
// Dice 1 to 6 code
MytextView.setText("1 to 6");
break;
case R.id.radioButton1to10:
if (checked)
// 1 to 10 code
MytextView.setText("1 to 10");
break;
}
}
And the 'private int getRandomNumber' at the end can be deleted. No need of it.

I want visible button has removed it text from TextView

I want visible button has removed it text from TextView
i am making keyboard typing in text view I have 4 buttons b1,b2,b3,backspace.
when I clicking on b1 typing in textview "A" and b1 invisible
then when I clicking backspace button its remove last char but does not appear last button has clicked
my project
https://youtu.be/_pLEUevM8aA
java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//my buttons
Button b1,b2,b3,backspace;
//my text view
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txt);
b1 = (Button)findViewById(R.id.b1);
b2 = (Button)findViewById(R.id.b2);
b3 = (Button)findViewById(R.id.b3);
backspace = (Button)findViewById(R.id.backspace);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
backspace.setOnClickListener(this);
}
//on clike listener
#Override
public void onClick(View view) {
switch (view.getId()){
//b1 on click
case R.id.b1:
txt.setText(txt.getText().toString() + b1.getText());
b1.setVisibility(View.INVISIBLE);
break;
//b2 on click
case R.id.b2:
txt.setText(txt.getText().toString() + b2.getText());
b2.setVisibility(View.INVISIBLE);
break;
//b3 on click
case R.id.b3:
txt.setText(txt.getText().toString() + b3.getText());
b3.setVisibility(View.INVISIBLE);
break;
//here is my problem last char has deleted button of that char must be get visible
//backspace on click
case R.id.backspace:
//I want visible button has removed it text from TextView
//appear last button has clicked
txt.setText(txt.getText().toString().substring(0,txt.getText().toString().length()-1));
break;
}//end switch
} //I hope get answer in this website
}
//thank for ALL helping
You could create a Stack of pressed buttons, so that you would know in which order they are pressed:
public class MainActivity extends ... implements ...{
Stack<View> pressedButtons = new Stack<>();
...
#Override
public void onClick(View view) {
// If it is a number, not a backspace key - remember that we pressed it
if(view.getId() != R.id.backspace) {
pressedButtons.push(view);
txt.setText(txt.getText().toString() + ((Button) view).getText());
view.setVisibility(View.INVISIBLE);
}
else { // backspace key
String text = txt.getText().toString();
if(text.isEmpty())
return; // do this to prevent crash
txt.setText(text.substring(0, text.length() - 1));
// make the button visible again
View lastPressedButton = pressedButtons.pop();
lastPressedButton.setVisibility(View.VISIBLE);
}
}
}
You can try this:
case R.id.backspace:
//try like this
if(string.substring(string.length() - 1).equals(b3.getText()))
b3.setVisibility(View.VISIBLE);
...
txt.setText(txt.getText().toString().substring(0,txt.getText().toString().length()-1));

Android Studio: Set dropped TextView to whatever was dragged

I am implementing a Drag and Drop interface with 6 Drag TextViews and 6 Drop TextViews.
Any 1 of 6 Drag views can be dropped onto any 1 of 6 Drop views.
An example would be if tvNum1=13, tvNum2=16, tvNum3=9, then I can drop any one of them onto tvSTR, tvDEX, or tvINT and set the respective Drop text to whatever was dragged. So if tvNum2 was dragged onto tvSTR, then tvSTR should show 16. Or let's say that instead you decided to drag tvNum3 onto tvSTR, then tvSTR should show 9. Each Drag view can only be used once.
Here's my current code. I can't find a way to make it so that the text of whatever was dragged is the text of the Drop view. I can only make (a 1-to-1 correlation) it so that if tvNum1 was dragged onto tvSTR, then tvSTR=13. Or if tvNum2 was dragged onto tvDEX, then tvDEX=16.
public class setCharacterRolls extends AppCompatActivity
{
// Variable declarations
private TextView tvNum1, tvNum2, tvNum3, tvNum4, tvNum5, tvNum6;
private TextView tvSTR, tvDEX, tvINT, tvWIS, tvCHA, tvCON;
String roll1, roll2, roll3, roll4, roll5, roll6;
// String roll1Num, roll2Num, roll3Num, roll4Num, roll5Num, roll6Num;
private Button bSubmit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_character_rolls);
// Get the previous intent
Intent intent = getIntent();
// Save the rolls from the previous screen onto a String to use later.
roll1 = intent.getStringExtra("roll1");
roll2 = intent.getStringExtra("roll2");
roll3 = intent.getStringExtra("roll3");
roll4 = intent.getStringExtra("roll4");
roll5 = intent.getStringExtra("roll5");
roll6 = intent.getStringExtra("roll6");
// Get TextView id's
tvNum1 = (TextView) findViewById(R.id.tDrag1);
tvNum2 = (TextView) findViewById(R.id.tDrag2);
tvNum3 = (TextView) findViewById(R.id.tDrag3);
tvNum4 = (TextView) findViewById(R.id.tDrag4);
tvNum5 = (TextView) findViewById(R.id.tDrag5);
tvNum6 = (TextView) findViewById(R.id.tDrag6);
tvSTR = (TextView) findViewById(R.id.tvSTR);
tvDEX = (TextView) findViewById(R.id.tvDEX);
tvINT = (TextView) findViewById(R.id.tvINT);
tvWIS = (TextView) findViewById(R.id.tvWIS);
tvCHA = (TextView) findViewById(R.id.tvCHA);
tvCON = (TextView) findViewById(R.id.tvCON);
// Set TextView to the roll numbers
tvNum1.setText(roll1);
tvNum2.setText(roll2);
tvNum3.setText(roll3);
tvNum4.setText(roll4);
tvNum5.setText(roll5);
tvNum6.setText(roll6);
// Set TextView to be draggable
tvNum1.setOnTouchListener(onTouch);
tvNum2.setOnTouchListener(onTouch);
tvNum3.setOnTouchListener(onTouch);
tvNum4.setOnTouchListener(onTouch);
tvNum5.setOnTouchListener(onTouch);
tvNum6.setOnTouchListener(onTouch);
// Targets to be dropped on
tvSTR.setOnDragListener(dragListener);
tvDEX.setOnDragListener(dragListener);
tvINT.setOnDragListener(dragListener);
tvWIS.setOnDragListener(dragListener);
tvCHA.setOnDragListener(dragListener);
tvCON.setOnDragListener(dragListener);
}
View.OnTouchListener onTouch = new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent mEvent)
{
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuild = new View.DragShadowBuilder(v);
v.startDrag(data, shadowBuild, v, 0);
return true;
}
};
View.OnDragListener dragListener = new View.OnDragListener()
{
#Override
public boolean onDrag(View v, DragEvent event)
{
int dragEvent = event.getAction();
switch(dragEvent)
{
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
final View view = (View) event.getLocalState();
switch(view.getId())
{
// This is where I have the 1-to-1 correlation.
// I want to be able to drag any draggable texview and set it to whatever it was dropped on.
case R.id.tDrag1:
tvSTR.setText(roll1);
break;
case R.id.tDrag2:
tvDEX.setText(roll2);
break;
default:
break;
}
break;
case DragEvent.ACTION_DROP:
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
default:
break;
}
return true;
}
};
}

Android tableview with dynamic numbers columns and rows

This is actually a memory training app, with matrix of squares wich flips to their other side and than back to first side. And user need to click on squares that flipped. You know what I mean?
Something like that.
What I need is that sizes of the matrix would change dynamically. If user have been passed one level of complexity (matrix size is 4x4 for example), then matrix size would grow (5x5 for example), and if not then matrix size would get smaller (3x3 for example). I hope that's clear, and if not - sorry, English is not my native language =)
So if I would do it from code this would not be a problem. I would use ViewFlipper with some transition animation and create TableView with sizes that I want with inflater or something like that (or directly from code without using xml at all). And then adding it to ViewFlipper from code.
But somehow I don't like that idea.
Then next idea come into my mind. To do ViewFlipper with all possible tableviews in it and then just showNext(); or showPrevious(); depending on what user have done. But in this case XML would be of very great size.
So maybe someone knows the another way to do it?
i suggest you to look view-pager-example,
using viewflipper showNext(); or showPrevious(); you had to download all data at the same time, but using fragmen, you can load only specific data assoiated with fragment.
you can change the view on every fragment like below
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new DetailFragment();
case 1:
return new ImageFragment(R.drawable.ic_launcher);
case 2:
return new ImageFragment(R.drawable.thumb);
default:
return null;
}
}
[EDIT - For checking view in listener]
public class LoginExampleImplements extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v==btn1) {
} else if(v==btn2) {
} else if(v==btn3) {
} else if(v==btn4) {
}
}
}
[EDIT 2]
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
LinearLayout1 = (LinearLayout) findViewById(R.id.LinearLayout1);
for (int i = 0; i < 30; i++) {
button = new Button(getApplicationContext());
button.setId(i);
button.setOnClickListener(this);
LinearLayout1.addView(button);
}
}
#Override
public void onClick(View v) {
Button b = (Button)v;
b.getId()
// check clikedId
}
[EDIT 3]
public class MainActivity extends Activity implements OnClickListener{
ImageView img;
LinearLayout LinearLayout1;
LinearLayout.LayoutParams layoutParams;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout1 = (LinearLayout) findViewById(R.id.ln1);
layoutParams = new LinearLayout.LayoutParams(100, 100);
for (int i = 0; i < 30; i++) {
img = new ImageView(getApplicationContext());
img.setId(i);
img.setTag(i);
layoutParams.setMargins(10, 10, 10, 10);
img.setLayoutParams(layoutParams);
img.setBackgroundColor(Color.RED);
img.setPadding(10, 10, 10, 10);
img.setOnClickListener(this);
LinearLayout1.addView(img);
}
}
#Override
public void onClick(View v) {
ImageView b = (ImageView)v;
b.setBackgroundColor(Color.BLUE);
b.setImageLevel(Integer.valueOf(String.valueOf(b.getTag())));
}
}

Android: roatating images in a loop

I am trying with no success to modify the code example from:
http://www.inter-fuser.com/2009/08/android-animations-3d-flip.html
so it will rotate the images in a loop, when clicking on the image once. (second click should pause).
I tried using Handler and threading but cannot update the view since only the main thread can update UI.
Exception I get from the code below:
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
[in 'image1.startAnimation(rotation);' ('applyRotation(0, 90);' from the main thread)]
package com.example.flip3d;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
public class Flip3d extends Activity {
private ImageView image1;
private ImageView image2;
private boolean isFirstImage = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image1 = (ImageView) findViewById(R.id.image01);
image2 = (ImageView) findViewById(R.id.image02);
image2.setVisibility(View.GONE);
image1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (isFirstImage) {
applyRotation(0, 90);
isFirstImage = !isFirstImage;
} else {
applyRotation(0, -90);
isFirstImage = !isFirstImage;
}
}
});
}
private void applyRotation(float start, float end) {
// Find the center of image
final float centerX = image1.getWidth() / 2.0f;
final float centerY = image1.getHeight() / 2.0f;
// Create a new 3D rotation with the supplied parameter
// The animation listener is used to trigger the next animation
final Flip3dAnimation rotation =
new Flip3dAnimation(start, end, centerX, centerY);
rotation.setDuration(500);
rotation.setFillAfter(true);
rotation.setInterpolator(new AccelerateInterpolator());
rotation.setAnimationListener(new DisplayNextView(isFirstImage, image1, image2));
if (isFirstImage)
{
image1.startAnimation(rotation);
} else {
image2.startAnimation(rotation);
}
}
}
How can I manage to update the UI and control the rotation within onClick listener?
Thank you,
Oakist
Try wrapping the UI code in runOnUIThread()

Categories

Resources