I need to add a switch (Android 4.0+) to my ListView , just a single switch with an ImageView Button , I have seen soo many tutorials that teach of adding several views in the list activities but what I need is just a single option of the list to have this switch . I know if I can put a button or textView I can put a switch in there , but I can't understand how is putting a button or any view there without repeating the whole same scenario on all the options , as for me , I am new to the ArrayAdapters and ListViews , but I need to learn these two so I can use them later on ! what I need is like this for example:
______________________
Image | Switch
______________________
Normal option
______________________
Button | Whatever view
_______________________
Normal option
_______________________
Checkable Option
_______________________
and so on ... So if you clearly , I want full control over every single option in there , thats what I need and want . Thanks for any help :)
if you're gonna do it by listview, then you can do it by being explicit about each position in the getView method of the adapter. here's an example:
public View getView(int position, View convertView, ViewGroup parent) {
switch (position) {
case 0:
// do image switch option
// convertView = layout 0
break;
case 3:
// do button whatever option
// convertView = layout 3
break;
case 5:
// do button whatever option
// convertView = layout 5
break;
default:
// do normal option
// convertView = layout 1
break;
}
return convertView;
}
getView is a method in many android adapters that returns a view. When hooked up to a listView, it will be recognized as the method to return a view for each one of its rows. Each row in a listview that you see is the product of one executed instance of this method. You don't call it: it is called automatically whenever rows of a listview need to appear, or whenever a row position moves off-screen and comes back, or whenever the listView is being refreshed, in general whenever listview rows must be "made". It is there for you to override so that you can customize how ever for the specific look that you want.
convertView is a view as well. It is the product of a concurrent mechanism running in the listview adapter called view-recycling. Imagine that you have a listview that needs to display 1000 rows for your game's shopping menu. a conventional approach would be that you simply make an inflate command for your in getView for a vibrant xml and edit the components to show the item differences. So, that's inflating a 1000 times (and inflating is a expensive step, mind you), plus all that has to be in memory and is just clogging up your garbage collector. Plus, what if you need to refresh something to show changes? Get outta here! There are quad-core phones now, but there is a better way.
listviews done right don't actually make 1000 views at once but only the 7 or 8 that are on the screen at a time. When a listview row view is scrolled beyond the boundaries of the phone's screen, it isn't thrown out just yet. This concurrent mechanism runs and this view is saved and held under the title of convertView and passed in as a parameter for the next getView call. Not to (re-)use it is a terrible waste, because essentially you have a view that looks like the next row in the next getView call, perhaps with only the text in a textview changed or something like that, but you're gonna do another expensive inflation anyway. Then the unused convertView knows that it's second chance has been disregarded, into the GC, and it's business as usual.
The above code doesn't make use of convertView, because frankly it wasn't asked in the question, but it's very simple to utilize.
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
// inflation step
// convertView = inflation
}
// rest of code involving components of inflated view
return convertView;
}
First you check if there's nothing there, which you can imagine is when a listview is first launched and nothing has had the chance to be on deck to be thrown out. And only then do your inflation then. Next time around, getView will have it's mouth full with used view and will plug it in (if it's being returned). This is the single most beneficial action for your listview performance-wise that you can do right off the bat.
But you should know this, about half the questions tagged android on this site are on this alone, there are no guarantees that convertView will plop in the position that you want, as in right below if you're scrolling up and right above if scrolling down. Just make sure that you're being explicit about what goes at what position and you'll be fine. For more information on this and other listview know-how watch this: http://www.youtube.com/watch?v=wDBM6wVEO70.
Related
I have created a view in which two views are included. Once a view as a waiting room (A) and in the second view (B), a call can be answered.
After a call has arrived at view A, the second view will be invoke (B). It works. If the user has finished the interaction he should get back to the view (A). Unfortunately that does not work.
Here is the code for invoke the view B. This works fine.
// Add view to content
OVSLobbyActivity.this.rootWaitingRoom.view.setVisibility(View.GONE);
OVSLobbyActivity.this.root.removeChild(OVSLobbyActivity.this.rootWaitingRoom);
OVSLobbyActivity.this.root.appendChild(OVSLobbyActivity.this.rootCallRoom);
OVSLobbyActivity.this.rootCallRoom.view.setVisibility(View.VISIBLE);
// Set fullscreen
OVSLobbyActivity.this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
OVSLobbyActivity.this.onWindowFocusChanged(true);
// force to change the layout
root.view.invalidate();
root.view.requestLayout();
Here is the code to hide the view B and show view A again. This does not work well. Here is the problem that only a white page will be shown. The elments inside the activity is missing.
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
this.onWindowFocusChanged(false);
this.rootCallRoom.view.setVisibility(View.GONE);
this.root.removeChild(OVSLobbyActivity.this.rootCallRoom);
this.root.appendChild(OVSLobbyActivity.this.rootWaitingRoom);
this.rootWaitingRoom.view.setVisibility(View.VISIBLE);
// force to change the layout
root.view.invalidate();
root.view.forceLayout();
root.view.requestLayout();
Do have any idea what is wrong?
Thank you for your help.
The solution is that the size of the view has to be recalculated. After the measures recalculated you have to execute following line:
this.view.requestLayout ();
After that the correct view will be shown.
I'm having hard time understanding working of view holder, here are my some question that could increase my understanding of viewholder:
It is said that oncreateViewHolder returns viewholder object, What is viewholder object does it contain all the views in single row? if there is list of 1000 item how many viewobjects will be created?
My understanding:
If we are creating viewholder object it contains reference of view like findviewbyid, since findviewbyid is expansive operation, so by viewholder we can create single viewholder object and reuse by just setting image or text(happens in onBindView).
But onCreateViewHolder runs multiple times and as a result findviewbyid will also execute multiple time, isn't performance issue?
Also how its different from convertView of base adapter of simple listview
Thanks!
View holder it is thing which helps u you to reduce find view by id calls.
Let give you an example.
Suppose you have 1k items, each have a 5 view you need to find by id and only 5 full items can be shown once at screen.
So, recyclerView will create 7 (5 + one not-full bottom and one not-full top) view holders. Next time when recyclerView will be scrolled it will use existing viewHolders. Exactly as name says : "RecyclerView"
So findViewById will be called 7*5=35 times.
If you do not use viewHolder you would get 5*1000 = 5000 calls.
35 vs 5000, so you understood I think.
It is said that oncreateViewHolder returns viewholder object, What is
viewholder object does it contain all the views in single row? if
there is list of 1000 item how many viewobjects will be created?
One ViewHolder object for one view row. One ViewHolder object is created for every time the onCreateViewHolder is called. It is called based on the number of visible items in the device. Even if you have 100 items, if ony 10 items are visible, the onCreateViewHolder will be called 10 times and there will be 10 ViewHolders. (There might be one or two extra item based on the RecyclerView optimizations because if you scroll the list, the next item should be visible instantaneously)
My understanding: If we are creating viewholder object it contains
reference of view like findviewbyid, since findviewbyid is expansive
operation, so by viewholder we can create single viewholder object and
reuse by just setting image or text(happens in onBindView).
RecyclerView is already recycling and reusing the Views and the corresponding ViewHolders. The number of ViewHolder (and View) present at any time depends on the number visible items on the screen.
But onCreateViewHolder runs multiple times and as a result
findviewbyid will also execute multiple time, isn't performance issue?
As said previously, the number of times this will be called is only for the number of visible items. When you scroll, the views and viewholders are reused. You have distinct Views for each row. So there will be distinct ViewHolder for each row.
Also how its different from convertView of base adapter of simple
listview
In ListView, the convertView is the old view, which provides an option to reuse the same view for new rows as you scroll the list. But it's optional because the developer might not use the convertView at all. In RecyclerView the reusing of old views is done automatically.
RecyclerView.ViewHolder is a helper class that holds the View of a row or rows.
One or more ViewHolder is created for each viewType.
if several rows have the same ViewType then the same View can be reused for several rows.
Overriding getItemViewType(int position) is the way to have several view types. If getItemViewType returns a not used before viewType then onCreateViewHolder will be called to create a new ViewHolder.
Adapter onBindViewHolder is the place to fill the view with specific data for each row.
ADDED:
A concept must be clear: what makes a ViewHolder to be reused is that it shares the same viewType.
Instead if you make getItemViewType(int position) return a different value for each row then each row will have its independent ViewHolder and view.
assume that you want to show a list of 1000 items and there are just 10 items visible to the user in the screen. your adapter creates 10 ViewHolder instances to show them at the same time. when user scrolls and the adapter has to show more items, instead of creating new instances of ViewHolder, it reuses items that are not visible anymore. your adapter prevents creating new Views and saves CPU time by doing so.
In the getView() method of my GridView, I am doing the following:
public View getView(int position, View convertView, ViewGroup parent) {
convertView = this.inflater.inflate(..);
ImageView image = (ImageView) convertView
.findViewById(R.id.imageButton1);
imageLoader.displayImage("URL/"
+ sampleArray.get(position), image);
sampleArray here is an array I've loaded when the Adapter is created. It is used when lazy-loading (with this tool: https://github.com/nostra13/Android-Universal-Image-Loader) these images and basically is a part of the image URL that determines the picture to load. Now, as far as I know, best practice is to do only inflate the view if it's null:
if(convertView == null){
this.inflater.inflate(...);
When I do this, it is infact faster, but the image loading is weird. If I scroll down and scroll back up, the images switch within the row, meaning in the top row, the 1st column image might randomly switch with the second column image. The array I am using (sampleArray) doesn't change. I know it has something to do with position and getView() being called, but I'm not sure why this behavior happens.
If I do it the way I am doing now (the first block of code), meaning I inflate it every time, it works perfectly but loads slowly. Why does this behavior work like this?
Thanks in advance.
EDIT:
Here's what I think is happening. GetView() is being called multiple times, which is somehow not in sync with the "position" argument, causing the wrong element to be picked out of the array. I'm still puzzled by it.
You should use
.resetViewBeforeLoading()
and probably
.showStubImage(R.drawable.empty_image)
on your DisplayImageOptions when you initialize the UIL.
This will reset the view before the loading.
This is needed because you are reusing the views on gridview.
Have you tried to clean up the original image:
image.setImageBitmap(null);
I check the source code of the image loader, one of the methods is like:
public void displayImage(String uri, ImageView imageView, DisplayImageOptions options)
I think you can also try to set the option as "resetViewBeforeLoading = true"
the reason I think that the weird thing happens is, the view is recycled by the gridview, which is still with the original bitmap when showing up, before the loader attach it with the new bitmap.
if it still doesn't work, please lemme know.
EDIT
I did more investigation, the reason I think is from the recycling.
Let me explain more clearly:
reason:
suppose we have total 12 cells in our data
on screen, there are only 9 views visible
at very beginning, the gridview will create and show 9 on screen:
view_1_1 view_1_2 view_1_3
view_2_1 view_2_2 view_2_3
view_3_1 view_3_2 view_3_3
after scrolling(scrolling up, to show the row 4), at the moment, grid view will put view_1_1, view_1_2, view_1_3 in recycle bin.
and then will get 3 views for row 4 from recycle-bin, which are put in the getView as "convertView"
so, the view_1_1, view_1_2, view_1_3 will be reused.
suppose at the beginning, the views are attached with bitmap
view_1_1 : bitmap_1_1
view_1_2 : bitmap_1_2
view_1_3 : bitmap_1_3
when these view are recycled and show at the row 4, since the bitmaps are loaded asynchronously, the bitmap_1_1, bitmap_1_2, bitmap_1_3 will show up on the row 4, and laterly be replaced by those new bitmap.
how to confirm it
1.one way for debugging grid view I like is put some "id" on the image, the simple way is just put "ImageView" toString()
put an overlay view above each imageView, and write id in it, like:
String s = viewInfoHolder.imageView.toString();
viewInfoHolder.overlay.setText(s.substring(s.length() -3));//last 3 chars are enough and cleanup
2.for making the replacement slow, modify the
com.nostra13.universalimageloader.core.LoadAndDisplayImageTask
the last row in method:
public void run()
from:
handler.post(displayBitmapTask);
to:
handler.postDelayed(displayBitmapTask, 2000);
and you could find out exactly how the grid view works.
Hope it helpful :)
I am working on a app that shows some places in a listview. In every listview item there is a arrow pointing towards the place(hotel, bar etc).
The problem is I don't know how to keep this arrow updated efficiently, without cashing views locally( which, according to a Google I/O video, is something i should never ever do).
The arrow needs to be updated on every phone orientation sensor event, which is many times a second.
So is there a better approach than calling notifyDataSetChanged() on every event and refiling every list item data?
UPDATE (for #dharan and anyone interested):
I have stopped working on this project because I have a full-time job now, but I thought of a solution (unimplemented/untested).
First limit the angle of rotation to a fixed step, (eg: 5, 10, 15, 20, ... 355, 360) then cache the rotated image for each angle of rotation in order to avoid expensive image rotation calculations (but at a higher memory cost).
After that I would make my getView() method know when to only update the image instead of all the data. In my case this is as easy as:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null && place[position].id == (Integer)convertView.getTag()){
//the place information is already set correctly so just update the image
}
...
}
After these modifications I believe that calling notifyDataSetChanged() should not cause serious performance issues.
If you don't have too many items in the ListView you could convert to using a plain LinearLayout and control those items individually. The problem with LinearLayout though is if an item changes its size then everything (ie all children) has to be relayed out. So triggering a change in one item can re-trigger other things to layout as well. Now because you're changing a compass needle you might be able to skirt around it because that shouldn't cause each row to change its overall size. You just need to repaint that item.
The other option is to write your own layout that takes some short cuts making some assumptions the general purpose layout managers can't. The last thing I might look at is what does notifyDataSetChanged() does under the covers. You might be able to extend ListView and write a method that only redraws the row that changed (of course this assumes the height of the row hasn't changed). If the row height changes then everything after that row has to be relayed out.
We are creating an app with two main views: sView and sViewSettings. If the Android Back button is pressed we want an if statment to check if the current view is set to sView settings, if it is then call the sView.
Already have a listener setup for the back button just need it to call the if statement to check the current view.
Have already tried
if (this.findViewById(android.R.id.content) == sViewSettings)
Any ideas on this?
Thank you for Reading,
Travis
The view with id android.R.id.content is a FrameLayout holding your content view. Try this:
ViewGroup contentFrame = (ViewGroup) findViewById(android.R.id.content);
if (contentFrame.getChild(0) == sViewSettings) { ... }
However, I suggest a slightly different approach: use a ViewSwitcher (or any kind of ViewAnimator) to flip between the two main views and keep track in your code of which one is on display.
EDIT: If you want to keep your layouts loaded separately, you can assign an id (the same one) to the root view of each layout and then retrieve the content view directly using findViewById.