I have a series of ImageViews that I programatically added into a LinearLayout, so they all end up horizontally lined up.
But when I try to use a TranslateAnimation to move all the images at once, a 1 pixel white gap flashes between every ImageView for about .02 seconds and then disappears. And this seems to consistently happen every 2 seconds or so.
TranslateAnimation moveLeft = new TranslateAnimation(0, -1250, 0, 0);
moveLeft.setDuration(10000);
moveLeft.setFillAfter(true);
I make my ImageViews all at the same time before I move them. (Also, the ImageViews have all default settings) I've also confirmed that there are no white gaps between the ImageViews before I move them.
The flickering only happens when I set all the ImageViews's animations to moveLeft.
Also, here is the class in question :
public class Terrain {
Bitmap tile;
InputStream is;
ImageView imageViewPlatform;
Drawable tileDrawable;
ArrayList<ImageView> terrainArray = new ArrayList<ImageView>();
ArrayList<TranslateAnimation> moveLeftArray = new ArrayList<TranslateAnimation>();
int count = 0;
int terrainBlockNumber = 0;
boolean initialized = false;
TranslateAnimation moveLeft;
public void initialize(Activity activity){
is = activity.getResources().openRawResource(+R.drawable.game_tile);
tile = BitmapFactory.decodeStream(is);
tileDrawable = new BitmapDrawable(activity.getResources(), tile);
moveLeft = new TranslateAnimation(0, -1250, 0, 0);
moveLeft.setDuration(10000);
moveLeft.setFillAfter(true);
initialized = true;
Log.d("Terrain", "Terrain images are initialized.");
}
public void draw(Activity activity, LinearLayout linearLayout,
LinearLayout.LayoutParams layoutParams) {
if (!initialized) {
throw new RuntimeException("initialize() method must " +
"be called before the draw() method.");
}else{
terrainArray.add(new ImageView(activity));
++count;
terrainArray.get(count-1).setImageDrawable(tileDrawable);
linearLayout.addView(terrainArray.get(count-1), layoutParams);
}
}
public void move(Activity activity) {
terrainBlockNumber++;
final int terrainAnimationBlock = terrainBlockNumber;
moveLeft.setAnimationListener(new Animation.AnimationListener() {
int currentCount = terrainAnimationBlock;
#Override
public void onAnimationStart(Animation animation) {
Log.d("Animation Started", "Block Number is " + currentCount);
}
#Override
public void onAnimationEnd(Animation animation) {
terrainArray.get(currentCount - 1).setVisibility(View.GONE);
Log.d("Terrain Deletion", "Block number " +
currentCount + " has been deleted.");
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
terrainArray.get(terrainBlockNumber - 1).startAnimation(moveLeft);
}
}
}
This is the XML file for the activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.project.PlayActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/linearLayout"
android:weightSum="1"
android:layout_alignParentTop="true"
android:layout_marginTop="200dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</LinearLayout>
</RelativeLayout>
UPDATE :
Moving the entire LinearLayout does not seem to work either. Although, moving the entire LinearLayout isn't really helpful. It cuts off ImageViews that are off-screen.
But since you requested it, all I did was change the move method to :
public void move(LinearLayout linearLayout){
linearLayout.setAnimation(moveLeft);
}
All the images did actually move at the same speed, and there is still the flickering between the images.
UPDATE 2
I have confirmed that it has something to do with my images/how they're formatted/the size of the images or something along those lines.
If it is any help, the image I use is 95 X 84 pixels. (It's really tiny)
If you have several images you might want to:
Use a RecyclerView. This gives you more control over animations and decorations, and optimizes the memory usage at the same time. This answer will help you understand how to make your animations.
Make sure you are not constantly resizing your images. If the animation needs to handle images that are originally too big, it might impact on the quality of the animation (i.e. use thumbnails and fixed sizes in order to avoid costly computations)
For instance, if your original images are 600x800 but your image
view has a centerCrop/fit/etc ending up occupying a space of 200x200,
android will be doing a lot of resizing to match those settings. The
more computations it does, the more chances you get of missing
frames. In other words: what you experience is a low framerate,
which happens when android is unable to finish all drawing
computations in time for the next screen refresh.
There are different problems you can attack:
Reduce the computations by using the right image sizes
Smaller images also mean less memory usage, which reduces the need of memory reallocation or forced garbage collection.
Avoid computing/rendering things that are invisible. Either because they are out of screen or because something overlaps them. In your case, recycler view might help to load only the images on your visible screen, instead of wasting space and computations on images that are out of sight at the moment.
Reduce the layout rewrite. Android tries to render only the sections with updates, instead of re-render all the screen. But if your layout forces other layouts to recalculate their size, you can end up forcing a whole resize. In your case, do not use LinearLayout to list images. Instead, use some layout that is actually designed for that sort of things. As I said, RecyclerView with the default LinearLayoutManager works very well.
Check if you have hardware acceleration turned on.
Try to put the ImageViews in a LinearLayout or other ViewGroup and animate the entire ViewGroup and see if that helps.
Related
I have at least 48 small images that are displaying a vector images stored as an XML file in drawable. I have a multi choice listview with 48 items. When an item is checked I access to its image counterpart and change the tint of the image. if less than (approximately) 30 items is checked, there is no problem, but if it's more than that, an OutOfMemoryError is displayed. Here is example of the code:
View.OnClickListener listener= new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
image = null;
if (checked.valueAt(i)) {
switch (position) {
case 1:
image = (ImageView) findViewById(R.id.image1);
image.setColorFilter(R.color.green);
break;
case 2:
image = (ImageView) findViewById(R.id.image2);
image.setColorFilter(R.color.green);
break;
case 3:
image = (ImageView) findViewById(R.id.image3);
image.setColorFilter(R.color.green);
break;
....
case:48
image = (ImageView) findViewById(R.id.image48);
image.setColorFilter(R.color.green);
break;
}
}
}
mybutton.OnClickListener(listener)
example of the images in xml file
<RelativeLayout>
<ImageView
android:layout_width="400dp"
android:layout_height="400dp"
android:src="#drawable/img45"
android:id="#+id/image1"
/>
<ImageView
android:layout_width="400dp"
android:layout_height="400dp"
android:src="#drawable/img45"
android:id="#+id/image2"
/>
....
<ImageView
android:layout_width="400dp"
android:layout_height="400dp"
android:src="#drawable/img45"
android:id="#+id/image48"
/>
</RelativeLayout>
It seems that the problem is common with Bitmap images, but the solution proposed in the previous questions does not suit my case. Do you think if I change the src of the images from an xml vector to a simple png would fix the problem? if not, Any suggestion?
You're creating a separate color filter for each image. Creating a single color filter and using it on all images would reduce object usage. But if the image view is immediately creating a new bitmap with the shading you're going to go OOM no matter what- you're creating 48 new bitmaps here, which is a huge amount of memory.
Secondly, every time you check a single item, you're creating new filters for all images. That's just horribly inefficient (especially since you have n time searches in each case) and would make the problems in the previous paragraph worse. Only change the single item that was clicked in each click handler. Doing it this war creates sum (i=1 to n) i new images where n is the number of images clicked- for n=30 that's 430ish.
As an aside- using a switch statement here is horrible. Create an array of imageViews at start time and index into the array, rather than using findViewById each time which does an O(n) search through your view tree. This code is pretty bad all around.
I am currently trying to do a pseudo-circular reveal that will work on Android API levels below Lollipop. So, I have a floating action button (FAB) that I want (when pressed) to move vertically into a RelativeLayout (before clicked it sits outside of the RelativeLayout) and then scale by a certain factor so that it looks like a reveal.
I thought that using .setClipBounds() on the FAB would limit the scale animation in the area of the RelativeLayout but unfortunately the scale animation expands to take over the whole Activity area. This is the code in the click listener of the FAB:
circleFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int cardHeight = relativeCardBuild.getHeight();
int cardWidth = relativeCardBuild.getWidth();
Log.i("RELAT H", "" + cardHeight);
Log.i("RELAT W", "" + cardWidth);
circleFab
.animate()
.translationY(-(cardHeight / 2))
.setInterpolator(new AccelerateDecelerateInterpolator())
.setDuration(200).start();
tickFab.animate().alpha(0.0f).setDuration(200).start();
circleFab.setClipBounds(new Rect(relativeCardBuild.getLeft(),
relativeCardBuild.getTop(), relativeCardBuild
.getRight(), relativeCardBuild.getBottom()));
Log.i("left ", relativeCardBuild.getLeft()+"");
Log.i("top ", relativeCardBuild.getTop()+"");
Log.i("right ", relativeCardBuild.getRight()+"");
Log.i("bottom ", relativeCardBuild.getBottom()+"");
circleFab.animate().setStartDelay(100).scaleX(20.0f)
.scaleY(20.0f).setDuration(500).start();
}
});
The logged values of the relativeCardBuild's left, top, right and bottom points are correct so I am indeed setting the clip bounds of the circleFab layout (it's a FrameLayout that contains an oval drawable and a bitmap drawable) correctly. Still, the scale animation takes up the whole activity screen.
Am I completely misunderstanding what .setClipBounds() does in this instance?
I'm trying to implement an animation which crossfades between 2 layout, with a layover between them. The first layout is the main layout, the second is a simple linear layout with textView and red background (your classic "Wrong!" screen if you will...). My goal is to animate a quick transition between the mainLayout and wrongLayout, have the program wait for a short period of time while displaying the wrongLayout and then automatically return to mainLayout. This turns out to be extremelly hard, I've tried using monitors, Thread.sleep() etc. but what I get is that the program waits before starting the animation and THEN performs it without any layover.
My code is as follows:
In the main method-
LinearLayout wrongLayout = (LinearLayout) findViewById(R.id.wrong_layout);
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
int animationDuration = getResources().getInteger(
android.R.integer.config_longAnimTime);
crossfade(wrongLayout, mainLayout, animationDuration);
/* This is where I want it to wait for 1 second */
crossfade(mainLayout, wrongLayout, animationDuration);
and the crossfade method-
private void crossfade(View fadeInLayout, final View fadeOutLayout,
int animationDuration) {
// Set the content view to 0% opacity but visible, so that it is visible
// (but fully transparent) during the animation.
fadeInLayout.setAlpha(0f);
fadeInLayout.setVisibility(View.VISIBLE);
// Animate the content view to 100% opacity, and clear any animation
// listener set on the view.
fadeInLayout.animate()
.alpha(1f)
.setDuration(animationDuration)
.setListener(null);
// Animate the loading view to 0% opacity. After the animation ends,
// set its visibility to GONE as an optimization step (it won't
// participate in layout passes, etc.)
fadeOutLayout.animate()
.alpha(0f)
.setDuration(animationDuration)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
fadeOutLayout.setVisibility(View.GONE);
}
});
}
Thanks a lot...
Ok, so I've found this post which deals with just about the same problem-
Why the Sleep executes first and than the code above it in android?
I've changed the appropriate execution function and now it seems to work properly, though I'm still puzzled by the fact that I cannot cause the code to stop at a designated location for a specific amount of time. Oh well...
I understand, that this is local problem, but I was fighting with it for 1 day and I want ask for your help.
I have such kind of "game", where user can move items by swype, in this case, we are doing swype from top to bottom. Items are actual ImageViews.
On the first image we can see 7 items before the actual swype
Item goes as down as he can, until he meets another item or border of the field (invisible now)
On the second image, items have been moved once to down (only those who didnt have obstacle moved, 4 of them)
And, final position of items after second swype:
Now the problem : I can't explain why, but exactly when I do first swype, from top to bottom, and apply to those 4 items which will move down the actual animation of transition to new position, they dissapear on half way and appear on the new place!
When I do any other swype, to any direction, any items are animated, there are no problems. Everything goes fine when I do second swype to bottom.
I checked and overchecked, animation is done properly, there comes right parameters, and there are no other ImageViews on the way of animation, but something is overlaying the animation exactly in case where there are obsticles on the top of ImageViews! This is just weird.
All needed code is following:
Animation void
private void moveItem(final FieldItem item, final float x, final float y) {
// item to animate, transition X, transition Y
final RelativeLayout.LayoutParams oldParams = (LayoutParams) item
.getLayoutParams();
TranslateAnimation animation = new TranslateAnimation(0.0f, x, 0.0f, y);
animation.setDuration(500);
animation.setFillAfter(true);
animation.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
item.invalidate();
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
item.clearAnimation();
//all following is just to remove old item from layout
//and put new item on the place where animation should have ended
//nothing which can affect, it works perfect with any other condition
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
itemSize, itemSize);
params.leftMargin = (int) (oldParams.leftMargin + x);
params.topMargin = (int) (oldParams.topMargin + y);
gView.rLayout.removeView(item);
putItem(1, params);
gView.rLayout.invalidate();
//it's only ArrayList which contains copies of all Layout's children
//of ImageView class, for providing field moves logic, can't affect
//also recounts how many imageViews are in children of Layout
updateField();
//shows right margins, right amount of items on the field, they are always recounted depending of RelativeLayout children
Log.i("my_log", "Pos change, from " + oldParams.leftMargin + "/" + oldParams.topMargin + " to " + params.leftMargin + "/" + params.topMargin);
Log.i("my_log", "Size of field: " + field.size());
}
});
item.startAnimation(animation);
}
Layout which is used in here:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clipChildren="false"
android:orientation="vertical" >
<com.crispy_chocolate.outofthebox.GameView
android:id="#+id/game"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clipChildren="false" />
</RelativeLayout>
So the question is - how can ImageView even dissapear during the local case of animation when in any other case the same methods work totally fine? Maybe someone will be kind to help me.
Apparently, it's some kind of a bug, because If I put any imageview to the bottom part of the screen, or write some text, animation starts to go completely OK. weird.
I have a ScrollView with a lot buttons. Each button is enabled when the user unlocks that button/level. I would like to focus the ScrollView on the latest unlocked button/level. See the screenshot below.
I found some functions like scrollTo() that could focus the ScrollView either at top, button or something like that but I would like to focus the ScrollView at certain places like the button ID that says Level 8 in the screenshot below. How would I go about doing this?
I think this should be good enough :
yourButtonView.getParent().requestChildFocus(yourButtonView,yourButtonView);
public void RequestChildFocus (View child, View focused)
child - The child of this ViewParent that wants focus. This view will contain the focused view. It is not necessarily the view that actually has focus.
focused - The view that is a descendant of child that actually has focus
First you need to know the position of item in scroll that has to get focus once you know that you can use following code to make that item focus
final int x;
final int y;
x = rowview[pos].getLeft();
y = rowView[pos].getTop();
yourScrollView.scrollTo(x, y);
refer this question
I agree with the benefits of previous answers. However, by experience, I have found this to be more complex than this. The setSelectionFromTop is very sensitive and often breaks if it is executed too early. This may depend on different reasons but the two primary reasons are that
If executed from within Activity lifecycle methods the views have not been loaded/configured yet.
View modifications triggered after the list move action seems to break the move. Probably overwriting some value before the move has been finalized due to a recalculation of the views.
The reasoning seems to apply for both setSelectionFromTop and setSelection() methods although
I tested mostly with setSelectionFromTop. smoothScrollToPosition() seems to be more robust, probably because it by definition changes the list position delayed whn doing the smooth scrolling.
Look at this example source code:
// Wee need to pospone the list move until all other view setup activities are finished
list.post(new Runnable(){
#override
public void run() {
list.setSelectionFromTop(selectedPosition, Math.max(0, Math.round(list.getHeight() / 3))); // Make sure selection is in middle of page, if possible.
// Make sure you do not modify (this or other) parts of the view afterwards - it may break the list move
// activityButtons.setVisibility(View.GONE);
}});
see: http://developer.android.com/reference/android/widget/ListView.html#setSelectionFromTop(int, int)
'int selectedLevel' holds the currently selected level, information is held in a Level class.
'values' is a list with all your levels, displayed by the list.
Example:
ListView lv = (ListView)findViewById(android.R.id.list);
int i = 0;
for (Level l : values) {
i++;
if (l.level == selectedLevel) {
lv.setSelectionFromTop(i, 200);
break;
}
}
try this
sc.post(new Runnable() {
public void run() {
sc.smoothScrollTo(x, y);
}
});
x the position where to scroll on the X axis
y the position where to scroll on the Y axis
Use this code, taken from this answer
private final void focusOnView(){
new Handler().post(new Runnable() {
#Override
public void run() {
your_scrollview.scrollTo(0, your_EditBox.getBottom());
}
});
}
Use this code, taken from my another answer
scrollViewSignup.post(new Runnable() {
#Override
public void run() {
int scrollY = scrollViewSignup.getScrollY();
scrollViewSignup.scrollTo(0, 0);
final Rect rect = new Rect(0, 0, view.getWidth(), view.getHeight());
view.requestRectangleOnScreen(rect, true);
int new_scrollY = scrollViewSignup.getScrollY();
scrollViewSignup.scrollTo(0, scrollY);
scrollViewSignup.smoothScrollTo(0, new_scrollY);
}
});
This code tries to smooth scroll and uses the standard behaviour of system to position to an item. You can simply change smoothScrollTo with scrollTo if you don't want the system to smooth scroll to the item. Or, you can use the code below only.
scrollViewSignup.post(new Runnable() {
#Override
public void run() {
scrollViewSignup.scrollTo(0, 0);
final Rect rect = new Rect(0, 0, view.getWidth(), view.getHeight());
view.requestRectangleOnScreen(rect, true);
}
});
Use the desired code block after trying, or, according to the need.