I would like to create an deferred loading adapter for use with a Gallery widget.
That is to say getView() returns an ImageView immediately, and later some other mechanism will asynchronously call its setImageBitmap() method. I did this by creating a "lazy" ImageView that extends ImageView.
public class GalleryImageView extends ImageView {
// ... other stuff here ...
public void setImage(final Looper looper, final int position) {
final Uri uri = looper.get(position);
final String path = looper.sharePath(position);
new Thread(new Runnable() {
#Override
public void run() {
GalleryBitmap gbmp = new GalleryBitmap(context, uri, path);
final Bitmap bmp = gbmp.getBitmap(); // all the work is here
handler.post(new Runnable() {
#Override
public void run() {
if (GalleryImageView.this.getTag().equals(uri)) {
setImageBitmap(bmp);
}
}
});
}
}).start();
}
}
When I scroll slowly in the Gallery, the center image keeps popping into the center. It's hard to explain, exactly, but it's really annoying. I also tried the same approach for a spinner adapter and it works perfectly there.
Any ideas?
The solution is to implement a more intelligent method of when to fetch thumbnails - it is pointless fetching thumbnails while the user is flinging through the list. Essentially you want something like that implemented in Romain Guy's Shelves application.
To get the most responsive Gallery you'll need to implement some form of in-memory cache and do the following:
Only set an image if it exists in the in-memory cache from your getView. Set a flag indicating whether the image was set or whether a download is required. You could also maintain a memory in a cache on the SD card and internal memory, and if a fling is not currently ongoing then show a low res (inSampleSize set to 16 or 8) version which will be visible when just scrolling through - the high res version will load when the user lets go and settles on an image.
Add an OnItemSelectedListener (and make sure to call setCallbackDuringFling(false) when initializing) that downloads new thumbnails for all the visible items that require a download only if the users finger is up (you can use getFirstVisiblePosition and getLastVisiblePosition to find the range of views visible)
Also when the user lifts their finger check to see 1. if the selected position changed since the user put their finger down and if so 2. whether a download was initiated due to your OnItemSelectedListener - if it wasn't then initiate one. This is to catch the case where no flinging occurs, and thus OnItemSelected never does anything because it is always called with the finger down in this situation. I'd use a Handler to delay starting the downloading by the animation time of your gallery (make sure to clear any delayed messages posted to this handler whenever onItemSelected is called or when you get an ACTION_DOWN event.
After an image is downloaded check if any visible views requested this image then and update those views
Also be aware that the default Gallery component does not properly implement View recycling (it assumes each position in the adapter has a unique view, and also clears the recycler of these items when they go offscreen making it pretty pointless). Edit: on more looking it isn't pointless - but it's not a recycler in terms of next/previous views, rather it serves to avoid having to call getView for the current views during layout changes.
This means the convertView parameter passed to your getView method will more often that not be null, meaning you'll be inflating a lot of views (which is expensive) - see my answer to Does a replacement for Gallery with View recycling exist? for some hints on that. (PS: I have since modified that code - I would use a different recycle bin for layout phases and scroll phases, in the layout phase place and retrieve the views in the layout recycle bin according to their position, and DO NOT call getView if the view you get from the bin is non-null since it will be exactly the same view; also clear the layout recycle bin after the layout phase -- this makes things a bit more snappier)
PS: Also be very careful with what you do in OnItemSelected - namely unless it's in the places mentioned above then try to do as little as possible. For instance I was setting some text in a TextView above my Gallery in OnItemSelected. Just moving this call into the same points as where I updated thumbnails made a noticable difference.
I have an answer for you!
When any of the setImage... methods are called on ImageView in internally a layout pass is requested, for example, setImageBitmap() as above is defined as such
public void setImageBitmap(Bitmap bm) {
setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));
}
which calls
public void setImageDrawable(Drawable drawable) {
if (mDrawable != drawable) {
mResource = 0;
mUri = null;
updateDrawable(drawable);
requestLayout(); //layout requested here!
invalidate();
}
}
which has the effect of the gallery 'snapping' to the center of the image thats currently closest to the center of the gallery.
What I have done to prevent this is have the View thats loading into the Gallery have a explicit height and width (in dips) and using an ImageView subclass that ignores layout requests. This works as the gallery still has a layout pass initially but does not bother doing this every time an image in the gallery changes, which I imagine would only need to happen if the gallery views had their width and height set to WRAP_CONTENT, which we dont. Note that as invalidate() is still called in setImageDrawable() the image will still be drawn when set.
My very simple ImageView subclass below!
/**
* This class is useful when loading images (say via a url or file cache) into
* ImageView that are contained in dynamic views (Gallerys and ListViews for
* example) The width and height should be set explicitly instead of using
* wrap_content as any wrapping of content will not be triggered by the image
* drawable or bitmap being set (which is normal behaviour for an ImageView)
*
*/
public class ImageViewNoLayoutRefresh extends ImageView
{
public ImageViewNoLayoutRefresh(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public ImageViewNoLayoutRefresh(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ImageViewNoLayoutRefresh(Context context)
{
super(context);
}
#Override
public void requestLayout()
{
// do nothing - for this to work well this image view should have its dims
// set explicitly
}
}
edit: i should mention that the onItemSelected approaches can also work, but as I needed to hook into that while flinging was taking place I came up with the above, which I think is more flexible approach
This might be a bug in the Gallery's onLayout method. Check out http://code.google.com/p/android/issues/detail?id=16171 for a possible workaround.
Related
I am trying to write a function that moves the view "who" from "from" to "to". But it doesn't work in some cases and in others it just starts and finishes in wrong positions. What did I do wrong by my using of this animation type?
private void moveFromToShow(View from, View to, View who, boolean repeat) {
t = new TranslateAnimation(from.getX(), to.getX(), from.getY(), to.getY());
if(repeat){
t.setRepeatMode(TranslateAnimation.INFINITE);
t.setRepeatCount(Animation.INFINITE);
t.setRepeatMode(TranslateAnimation.RESTART);
}
t.setDuration(3000);
t.setFillAfter(true);
t.setZAdjustment(TranslateAnimation.ZORDER_TOP);
who.bringToFront();
who.startAnimation(t);
currentFreeAnimIndx++;
}
edit-explantion:
For example I have 2 views and want the image that is inside one of them to move to the other view. I send moveFromToShow(view1, view2, view1.getChildrenAt(0)); and I get the animation from near to view1(but not even exactly it) moving to outside of the screen.
I wanted this function to be universal for moving view from one to other view.
I have a card a game in which the person chooses the card and drags (done through translate animation) and then when let go it moves to the center of the screen where have an imageView place holder. At the animationEnd I set the image view to that card and can invalidate on each view on the screen. What I dont understand is that when I call invalidate then the card looks like it left some trails (shadows from the translate animation). When I call postInvalidate, it gets drawn properly. Why is that??
AnimationEnd code:
#Override
public void onAnimationEnd(Animation arg0) {
if(card == null){
MyApplication.SWERR(null);
busy = false;
}
card.getCardImage().setVisibility(View.INVISIBLE);
Drawable drawable = card.getCardSuitNumber().getDrawable(mContext);
finalDestIV.setBackgroundDrawable(drawable);
finalDestIV.setVisibility(View.VISIBLE);
invalidateAll();
PlayerStatus p = mGameMonitor.getPlayerStatusFromPlayerEnum(GameConstants.PLAYERS.P1);
p.handleCardChosen(card);
cardReleased = false;
p.setPlayerLock(false);
card = null;
}
InvalidateAll method
private void invalidateAll(){
rootLayout.postInvalidate();
for (int i=0; i<rootLayout.getChildCount();i++){
View v = rootLayout.getChildAt(i);
v.postInvalidate();
}
}
Typical problem of novice Android developers.
Please look into the description of the invalidate method.
According to the Google documentation:
Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future. This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
So, I suppose onAnimationEnd is calling from non-UI thread (probably animation thread).
I think if you avoid the API policy it may lead to unexpected behavior and may differs between different Android versions.
Calling invalidate from non-UI thread can interrupt some UI operations (or brake some logic) in Android system which makes some misbehavior.
Look also here: What does postInvalidate() do?
I'm a little bit stuck with this one - first and foremost, the following link has been useful however I've come up with a bit of an issue with visibility:
The link: Check view visibility
I have a scroll view (parent) and a number of sub-views (LinearLayout -> TableLayout) etc. There are a number of items I set to View.GONE within the XML (android:visibility="gone").
I have some simple code to determine whether it is visible or not using getVisibility() however when I set the item to View.VISIBLE and try to immediately getDrawingRect() I get a Rect with zeros across the board. Any further click gets the correct coordinates.
Now this could be because the view has never been drawn (as defined in the XML) causing it to return no coordinates however I do set View.VISIBLE before trying to determine screen visibility. Could it be that I need to get some kind of callback from say the onDraw()? or perhaps set the view visibility of hidden items within code. A bit annoying ;(
Some code:
Rect scrollBounds = new Rect();
scroll.getHitRect(scrollBounds);
Rect viewBounds = new Rect();
if (view.getVisibility() == View.GONE) {
view.setVisibility(View.VISBLE)
viewBounds.getDrawingRect(viewBounds);
if (!Rect.intersects(scrollBounds, viewBounds) {
// do somthing
}
}
Layouts area as follows:
ScrollView
LinearLayout
TableLayout
Button
HiddenView
Of course, it's highly likely I'm going about this the wrong way altogether - basically I just want to make sure that the scrollview positions itself so the view that has become visible can be seen in it's entirety.
If any other information is required, let me know!
Ok so thanks to OceanLife for pointing me in the right direction! There was indeed a callback required and ViewTreeObserver.OnGlobalLayoutListener() did the trick. I ended up implementing the listener against my fragment class and picked it up where I needed it. Thanks for the warning too regarding the multiple calls, I resolved this using the removeOnGlobalLayoutListener() method - works a charm.
Code:
...
// vto initialised in my onCreateView() method
vto = getView().getViewTreeObserver();
vto.addOnGlobalLayoutListener(this);
...
#Override
public void onGlobalLayout() {
final int i[] = new int[2];
final Rect scrollBounds = new Rect();
sView.getHitRect(scrollBounds);
tempView.getLocationOnScreen(i);
if (i[1] >= scrollBounds.bottom) {
sView.post(new Runnable() {
#Override
public void run() {
sView.smoothScrollTo(0, sView.getScrollY() + (i[1] - scrollBounds.bottom));
}
});
}
vto.removeOnGlobalLayoutListener(this);
}
Just got to do some cleaning up now ...
So, if I am reading this right the issue you are having is that you want to find out the dimensions of some view in your layout to find out whether you have an intersection with the parent ScrollView.
What I think you are seeing (as you alluded to) is the instruction to draw the view being dispatched, and then in some sort of race-condition, the renderer resolving the measurements for the layout and the actual render where view objects get real sizes. One way to find out what sort of dimensions a view has on screen is to use the layout tree-listener. We use this observer to resolve a screen's dimensions when leveraging the Google Charts API, which requires a pixel width and height to be defined... which of course on Android is probably the biggest problem facing developers. So observe (pun intended);
final ViewTreeObserver vto = chart.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
/**
* #see android.view.ViewTreeObserver.OnGlobalLayoutListener#onGlobalLayout()
*/
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
if (view.getVisibility() == View.GONE) {
view.setVisibility(View.VISBLE)
viewBounds.getDrawingRect(viewBounds);
if (!Rect.intersects(scrollBounds, viewBounds) {
// do something
}
}
}
});
Word of warning the onGlobalLayout will get called multiple times as the renderer closes in on the final solution. The last call is the one we take.
This will provide you with a mechanism for performing actions on a drawn view like getting a view component's width and height. Hope that helps you out.
Aside: The clever chaps over at Square have designed a FEST hamcrest library that will allow you to write a test for this alongside Robotium. Check it out.
I have a UI where the root layout is a RelativeLayout. It has a number of Views, such as fields, buttons, etc.
There are also two other panels that are initially invisible. When the user clicks a button, one of these panels slides in from the left, another slides in from the bottom. The problem is the frame rate is pathetic on a Nexus S.
I want to use setDrawingCacheEnabled(true) in order to (I hope) speed up the animation of these two panels. As a simplified example, here is roughly how I slide in one of these panels. I'll call it "detailPanel".
public class MyActivity extends Activity {
// Initially invisible.
private View detailPanel;
// A simple slide animation.
private Animation detailEnterAnimation;
...
public void someButtonClicked(View view) {
detailPanel.startAnimation(detailEnterAnimation);
detailPanel.setVisibility(View.VISIBLE);
detailPanel.setDrawingCacheEnabled(true);
}
}
Now in the DetailPanel I try to use the cache. I was hoping that bitmap rendering via the cache would improve performance:
public class DetailPanel extends LinearLayout {
public void draw(Canvas canvas) {
Bitmap cache = getDrawingCache();
if (cache != null) {
canvas.drawBitmap(cache, 0, 0, null);
} else {
super.draw(canvas);
}
}
}
The Bitmap is non-null and is the right size, but it is completely black.
Why is my bitmap black? That code may be obscenely wrong; I've tried a million different things and just cannot figure it out.
From Android documentation (http://developer.android.com/reference/android/view/View.html#setDrawingCacheEnabled%28boolean%29):
Enabling the drawing cache is similar to setting a layer when hardware acceleration is turned off. When hardware acceleration is turned on, enabling the drawing cache has no effect on rendering because the system uses a different mechanism for acceleration which ignores the flag. If you want to use a Bitmap for the view, even when hardware acceleration is enabled, see setLayerType(int, android.graphics.Paint) for information on how to enable software and hardware layers.
Maybe this is your case?
You may want to build your drawing cache before using it, otherwise It will give you a blank bitmap
public void someButtonClicked(View view) {
detailPanel.startAnimation(detailEnterAnimation);
detailPanel.setVisibility(View.VISIBLE);
detailPanel.setDrawingCacheEnabled(true);
detailPanel.buildDrawingCache(); //may be you need to add this?
}
I would like to know what the best way would be to draw a background image (this would be pretty much static) and a foreground object which would move depending on user input in Android?
Sort of like a side-scroller game (when the foregroudn object needs to animate and change a lot more than the background).
TIA
You could set the background image as main view with setContentView. For drawing foreground image You could use custom class that extends View and do drawing in it "onDraw" method. Something like this:
class ForegroundImage extends View
{
public Foreground(Context ctx) {}
public void onDraw(Canvas c)
{
//here You draw image anything You want on canvas
}
}
ImageView lBackgroundImage = (ImageView)findViewById(R.id.BackgroundView);
setContentView(lBackgrounImage);
ForegroundImage lForegroundImage = new ForegroundImage(this);
addContentView (lForegroundImage);
I hope this helped