The purpose of this is to create SimonSays game and do the logic behind generating and displaying a pattern that needs to be repeated
sequenceArray is already populated with random values from 0 to 3, using Random class and for loop, then what I want to do is read depending on the case of each element of the sequenceArray array, I want to change one of 4 views in a way that the animation lasts 200 ms and it should give the end user a feeling of pressing a button, or in this case, a button flashing. Here's how I did this:
for(int j = 0; j < sequenceArray.length; j++){
switch(sequenceArray[j]){
case 0:
Drawable backgrounds_yellow[] = new Drawable[2];
Resources res_yellow = getResources();
backgrounds_yellow[0] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_yellow);
backgrounds_yellow[1] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_yellow_blink);
TransitionDrawable crossfader_yellow = new TransitionDrawable(backgrounds_yellow);
ImageView ivYellow = (ImageView) findViewById(R.id.iv1);
ivYellow.setImageDrawable(crossfader_yellow);
crossfader_yellow.startTransition(0);
crossfader_yellow.reverseTransition(200);
case 1:
Drawable backgrounds_red[] = new Drawable[2];
Resources res_red = getResources();
backgrounds_red[0] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_red);
backgrounds_red[1] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_red_blink);
TransitionDrawable crossfader_red = new TransitionDrawable(backgrounds_red);
ImageView ivRed = (ImageView) findViewById(R.id.iv2);
ivRed.setImageDrawable(crossfader_red);
crossfader_red.startTransition(0);
crossfader_red.reverseTransition(200);
case 2:
Drawable backgrounds_blue[] = new Drawable[2];
Resources res_ = getResources();
backgrounds_blue[0] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_blue);
backgrounds_blue[1] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_blue_blink);
TransitionDrawable crossfader_blue = new TransitionDrawable(backgrounds_blue);
ImageView ivBlue = (ImageView) findViewById(R.id.iv3);
ivBlue.setImageDrawable(crossfader_blue);
crossfader_blue.startTransition(0);
crossfader_blue.reverseTransition(200);
case 3:
Drawable backgrounds_green[] = new Drawable[2];
Resources res_green = getResources();
backgrounds_green[0] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_green);
backgrounds_green[1] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_green_blink);
TransitionDrawable crossfader_green = new TransitionDrawable(backgrounds_green);
ImageView ivGreen = (ImageView) findViewById(R.id.iv4);
ivGreen.setImageDrawable(crossfader_green);
crossfader_green.startTransition(0);
crossfader_green.reverseTransition(200);
default:
return;
}
I've tried the same code with OnClickListener shown bellow and it works, but for some reason, when I run the code above, nothing happens, no animation change takes place.
I've tested the sequenceArray afterwards, it isn't empty, but for some reason beyond my comprehension the current code just won't do what I want it to. What's the main difference between the for loop shown below with the logic above?
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Drawable backgrounds[] = new Drawable[2];
Resources res = getResources();
backgrounds[0] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_yellow);
backgrounds[1] = ContextCompat.getDrawable(MainActivity.this, R.drawable.simonsays_yellow_blink);
TransitionDrawable crossfader = new TransitionDrawable(backgrounds);
ImageView image = (ImageView) findViewById(R.id.iv1);
image.setImageDrawable(crossfader);
crossfader.startTransition(0);
crossfader.reverseTransition(200);
}
});
Related
I want to add images from asses to an imageview automatically. the below code does work well when images are in a drawable folder, but I want to create a separate folder name avatar in the asset folder and get random images from there in my imageview.
int[] images = new int[] {R.drawable.image01, R.drawable.image02, R.drawable.image03};
// Get the ImageView
setContent(R.layout.main);
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
// Get a random between 0 and images.length-1
int imageId = (int)(Math.random() * images.length);
// Set the image
mImageView.setBackgroundResource(images[imageId]);
Thanks in advance.
I suggest you to use AssetManager.list()
To list all the assets for the given folder within /assets folder, we use AssetManager.list(). Suppose we have some files within /assets/img and we need to list all those files, then we write code as follows.
String[] imgPath = assetManager.list("img");
Here we get String array of file names within img directory.
try {
String[] imgPath = assetManager.list("img");
for (int i = 0; i< imgPath.length; i++) {
InputStream is = assetManager.open("img/"+imgPath[i]);
Log.d(TAG, imgPath[i]);
Bitmap bitmap = BitmapFactory.decodeStream(is);
imageViewbyCode = new ImageView(this);
imageViewbyCode.setImageBitmap(bitmap);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
imageViewbyCode.setLayoutParams(params);
myLayout.addView(imageViewbyCode);
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
Please try below code:-
AssetManager assetManager = getAssets();
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
InputStream inputStream = assetManager.open("yourimage.jpg")
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
mImageView.setImageBitmap(bitmap);
I am randomizing the location of a button on a Relative View everytime a button is clicked. I am doing this by changing the margins of the buttons programatically as shown in the code:
Button testbtn = findViewById(R.id.testbtn);
testbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get Screen size
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
//Save dimensions in variables
int widthScreen = metrics.widthPixels;
int height = metrics.heightPixels;
TextView width_height = findViewById(R.id.width_height);
//Declare random
Random randomDimension = new Random();
//Declare layout params
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params.rightMargin = 608;
params.leftMargin = 428;
params.topMargin = randomDimension.nextInt(height) +1;
//params.setMargins();
buttonIDs[1].setLayoutParams(params);
width_height.setText(params.leftMargin+" "+params.rightMargin);
}
});
In this case, "buttonIDs[]" is an array i declared earlier in the class and "testbtn" is the button that when pressed, randomizes the position of my button.
However, these specific margins produce the following image
enter image description here
and I need:
enter image description here
Does anyone know why this is happening and how to fix it?
You set:
params.rightMargin = 608;
params.leftMargin = 428;
So the device must be 608+428+width of the button at least wide. Is it?
I wanted to put dynamically the checkboxes with the names that I retrieve from the API one below the other, but when I run the code the checkbox I see just one and the others are in the back of it
JSONObject json = new JSONObject(result);
arr = json.getJSONArray("functionality");
for(int i = 0; i < arr.length(); i++) {
String name = arr.getJSONObject(i).getString("name");
CheckBox check = new CheckBox(rootView.getContext());
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
check.setLayoutParams(lparams);
check.setText(name);
container.addView(check);
}
change below line in your code:
CheckBox check = new CheckBox(rootView.getContext());
to
CheckBox check = new CheckBox(container.getContext());
EDIT: CODE NOW FIXED
I'm trying to create a dynamically populated frame animation for a simple slot reel. I create a random sequence of 50 animated images to make it look like the reel is spinning, then add the final three symbols at the end.
My problem is that each time this method is run, it adds the frames onto the previous Animation. The first time it is run, the animation has 53 frames, the second time it has 106 frames, etc. I want to reset/clear the animation each time it is run, but I cannot figure out how to do so. If anyone has any ideas it would be greatly appreciated!
private void animate(int r1c1, int r2c1, int r3c1, int r1c2, int r2c2, int r3c2, int r1c3, int r2c3, int r3c3) {
ImageView imgView = (ImageView)findViewById(R.id.animationImage);
imgView.setVisibility(ImageView.VISIBLE);
AnimationDrawable frameAnimation = new AnimationDrawable();
BitmapDrawable cherry = (BitmapDrawable)getResources().getDrawable(R.drawable.cherry);
BitmapDrawable grape = (BitmapDrawable)getResources().getDrawable(R.drawable.grape);
BitmapDrawable lemon = (BitmapDrawable)getResources().getDrawable(R.drawable.lemon);
BitmapDrawable lucky7 = (BitmapDrawable)getResources().getDrawable(R.drawable.lucky7);
BitmapDrawable watermelon = (BitmapDrawable)getResources().getDrawable(R.drawable.watermelon);
BitmapDrawable orange = (BitmapDrawable)getResources().getDrawable(R.drawable.orange);
BitmapDrawable[] symbols = {cherry,watermelon,grape,lemon,orange,lucky7};
// frameAnimation = (AnimationDrawable) imgView.getBackground();
for(int i = 0; i < 50; i++) {
frameAnimation.addFrame(symbols[(int)(Math.random() * 6)], 50);
}
frameAnimation.addFrame(symbols[r3c1], 200);
frameAnimation.addFrame(symbols[r2c1], 200);
frameAnimation.addFrame(symbols[r1c1], 200);
imgView.setBackgroundDrawable(frameAnimation);
if (frameAnimation.isRunning()) {
frameAnimation.stop();
frameAnimation.selectDrawable(0);
frameAnimation.start();
}
else {
frameAnimation.start();
}
}
Here is my frameanimation.xml file
<animation-list
xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true">
</animation-list>
To clear the animation from any view you can use view.clearAnimation()
Provide your complete code for more clearification.
You can try this: Reset its drawable resource and restart animation.
if (frameAnimation.isRunning()) {
frameAnimation.stop();
imgView.setBackgroundDrawable(null);
imgView.setBackgroundResource(R.drawable.frame_animation);
frameAnimation.start();
}
Or you can use selectDrawable:
if (frameAnimation.isRunning()) {
frameAnimation.stop();
frameAnimation.selectDrawable(0);
frameAnimation.start();
}
Hope this helps.
I have a specific problem which has not be answered yet on stackoverflow; I have images in the assets folder numbered like 0.jpg, 1.jpg, 2.jpg etc. Using a for loop I select three images from the asssets folder and I am trying to add these images to a gridview but the images are not showing. The activity starts up okay just no images!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
gridView = (GridView) findViewById(R.id.gridview_result);
// Sets the Tag
gridView.setTag(GRIDVIEW_TAG);
/*
* Adapt the image for the GridView format
*/
imageAdapter = new ImageGridViewAdapter(getApplicationContext());
gridView.setAdapter(imageAdapter);
// Set the orientation to landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// Retrieve 3 images form the database which appear
// similar
for (int i = 0; i < 3; i++) {
// System.out.println(Retrieval.distances[i][0]);
image = Retrieval.distances[i][0];
int num = (int) image;
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(num);
String imageNum = sBuilder.toString();
System.out.println(imageNum);
String file = imageNum + ".jpg";
try {
// get input stream
InputStream ims = getAssets().open(file);
Log.i("ERROR_IMS", ims + "");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, file);
// set image to ImageView
gridView.setBackground(d);
Log.i("ERROR_d", d + "");
Log.i("ERROR_gridview", gridView+"");
} catch (IOException ex) {
Log.e("I/O ERROR", "Failed when ...");
}
}
}
I believe the issue is occurring in the try/catch. Any help will be much appreciated!
You should get all images first and set it to your adapter.
// set image to ImageView
gridView.setBackground(d);
doesn't affect to your grid items view.
A good tutorial for it: guide