Android List view with clickable button
Вставка
- Опубліковано 25 лип 2024
- In this video I go over how to make a listview with items that contain clickable buttons. Also dicusses view recycling and the viewholder pattern.
Link to github to download project source code:
github.com/jonndavis1993/Andr...
Awesome tutorial. Been searching for this solution all over for hours on stack overflow and finally found a clear and concise solution.
Thank you, very helpful! I also searched several sites for hours to find an example for exactly this problem (listview item+button both clickable with id) and this is the simplest and best explained tutorial I've found so far.
I'll watch it a couple more times now to get it burned in ;-)
Thanks Jonathan! You helped me big time, especially I found useful viewHolder logic in my project.
Great tutorial, my buttons didn't work while my items did. Now i know why. Thank you!
Life Saver! Was looking for how to make the button of each item interact with data from that save item. Using this method worked perfectly. Thanks!
Great tutorial, support and thanks also for sharing the code in GitHub. Nice also that you included the fix for the problem with the item positions.
great tutorial man! in my case the converView was always Null so i had to put my logic accordingly. in any case, thx for the help! works perfectly
Thanks a lot for the best tutorial on UA-cam on this topic!
looking for more practical tutorials !
That was great
thank you for mentioning this: android:descendantFocusability="blocksDescendants" Because without that my ListView wasn't responding to clicks (when my button was active). That problem has been killing me for days till I watched your video. THANK YOU!!
Definitely enjoyed your video, very helpful and you explain the purpose of many lines of code. Thank you!
Thank you for this awesome line: android:descendantFocusability="blocksDescendants"
Thanks !! Works like a charm with updated code.
Thank you very much for descendantFocusability! It helped me.
Thank you for this awesome line: android:descendantFocusability="blocksDescendants". It helped a lot!
still an amazing video even after 5 years !!!!!
very good tutorial! I was searching for such solution for long time !
Thanks dude!!! You've saved me full week's migraines
Thanks dude! Works perfectly!
Amazing tutorial, thank you!
This is AWESOME, thank you!
This helped me a lot! thank you for this video
Wonderful guide, thank you so much :)
Awesome tutorial. Good Job.
How to do it with SQLite data
Oh, thank you, you saved my future career)
Wonderful and helpful video, thank you!
Great tutorial!. Thanx. Would you please do a tutorial on Contextual Menu on listView; I wish not to have long press on contextual Menu. I wish just a touch would give me floating Menu. Or may be pop up menu in the listView?
thank you so so much this line helped me ,android:descendantFocusability="blocksDescendants"
Nice clear tutorial, thanks
thanks so much for this very clear tutorial
Very helpful. Thank you. I'd love to see a video on how to deal with a listview that has a large number of items.
+Duane Forster The content in this video applies to list of indefinite length.
+Duane Forster Encapsulate it inside a Scrollview instead of Relative Layout. Now you can just scroll all the way down to as many list items as there is.
I haven't tested it but it seems how it'd work.
MattBee2k2 Duane Forster You should never put a ScrollView inside of a ListView. View this link: developer.android.com/reference/android/widget/ScrollView.html
Excellent tutorial, thanks
Thank you very much.
Wonderful video. Very Helpful.
Thank YOU !!!! You are THE BEST !!!
You did an awesome job!! Thanks a lot... But If I put this two classes in separate file then it want's to declare the viewHolder instance with final keyword which causes problem for me.
It works, thank you.
Thanks for video, it really helped allot
If you have a problem about the position keep resetting after 9, the answer:
Modify the data if the view is null or not. If the view is null, then deflate and modify the values of the view. If not, the modify the values of the view.
Lets just put only 2 lines in the if:
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
}
//Do the remain here
The answer is from magallanes, StackOverFlow
Thanks to him 👍
In the tutorial at 12:50 when a button is clicked a Toast appears from inside the button's onClick method. But what if we want to return the clicked button's position to the parent activity, so that we call call a method from there?
You are the best!!!
Thank you man!!!
Thanks useful and well explained
thanks man for the awesome page
Hey, why does scrolling down to the bottom of the list change the order of the buttons position to random? the item list doesnt change positions but the delete does, only after scrolling to the bottom/past row 9.
what do you mean the buttons position to random?
+Jonathan Davis (iBlacklegend) As in the when u clicked the button ( the number of the position was random/changed). Anyway i fixed it by only bracketing the layoutinflater and convertview in the if(convertView == null) statement and removing the else.
Run your code then scroll to the bottom then check the if the number outputted when clicking the list and the button on the same row are the same. For me the Value in buttons were swapped around. eg when i clicked list item in row 1 it would give be position = 0 and when i clicked button in row 1 it would give be position = 0 BUT after i scrolled to the bottom, row 1 list item position was still = 0 and row 1 for button would change to a random value.
:/ im horrible at explaining sry
+monjenvely i am facing the same problem! how did you fixed this can you please explain more ?
probably because reused view contained old listener, and displayed text that it was assigned at creation, but when it got reused, the listener hasn't been changed and showed text for it's position in its "previous life".
the listener is written in if block ..it should be either in else block or out of the scope of if and else
Thank you! you saved my life
No problem. Please make recommendations for other tutorials and I'll try my best to make one.
Can you set your button with backround tint? I have problem with that, my background tint in button listview did not work, if in general layout worked, i tested in lolipop
Gracias por el vídeo :3
Nice tutorial.
Hi, you saved my life. Also, we accidentally share the same profile picture. Hi fellow DeadPool :D
thanks a lot for your help
Can i start a new activity on button click inside view holder?
best implementation
Hi Jonathan. Thanks for the great tutorial. I wish to implement some data from the database to the android app. I managed to loop and get the data that I wanted by using HTTP Client - Asynctask. However, fetching the data is slower than the creation of the list such that the data is only added to the array list after the list have been created. Hence, no information from database is shown. Is there a way to fetch my data from database before the list is created?
Yeah this is very simple to do. One you recieve the data from your database post a runnable using a handler on the UI thread, to set the adapter on the ListView. A better solution is to use a Loader (they were designed for loading data asynchronosly and displaying it to the UI when its finished). There is a very great tutorial by Alex Lockwood that goes into depth on the topic of Loaders and building your own.
Please help me I can't set the New Text to my firebase mebu ıtem.I can set the New Text in my android stuido manually.However this is not working with firebase.
Good Video, Thank you
Gosh i realized my brain cant keep up with this video.... way too advance for me....... Me and my stupid brain, thank you sir.
thank you so much :)
i want some items that should not clickable in listview...... how can i do that?
The listView element scrolls very slowly using how do I fix it?
Is there a way to change the image next to the text in the list and have a different image for each item? thanks
Yeah, you can load any image you want, it could even be a video if you'd like. You need to hande the loading logic inside of the getView(...) method.
seems that data is not getting populated in listview as the test next to image is always be "New Text". But it should get changed. Any help on this?
+Manas Singh The problem is probably in your getView() method of the list adapter.
+Jonathan Davis (iBlacklegend) even in this tutorial the text next to image is not getting populated... it's remaining the same as "New Text" (can be seen in the end of the tutorial when app runs on emulator), even its using some function to generate data.
+Manas Singh As was my initial suspicion, the problem was tied to the getView method. The code inside of else bracket, was preventing the textview from having it''s text set. Eventually if you scrolled the list until views started to be recycled and convert view was no longer null you would see the correct text.
So to fix the error would be to just remove the else statement brackets from getView so that it is always executed.
+Jonathan Davis (iBlacklegend) Thanks a lot, worked great!
+Manas Singh the code for setting text is missing within the if(convertView == null). That's why no text was set at initiation. Add viewHolder.textView.setText(getItem(position).toString()). Then it should work.
There is a problem in this code that when i scroll the items the position gets reset.
what listView is ListView lv = (ListView) findViewById(R.id.listview); referencing? there was no list view in the layout file.
Hello bro, excelent video!! I have a question, how can I implement a new activity for every button? Example: I clicked one button then the action display a new activity with new information. but in a different button , display a new activity with new information.
Why generic list contains string type, it should contains button type as we want to make a list of buttons clickable and every button have onclicklistener attach to them. Please explain, thanks in advance
how to use only button in listview to update the badge count which is in action bar???
Inside of the OnClick listener of the button manually manipulate the badge counter nested inside of your action bar.
hello. pls make a tutorial on searching for and highlighting a word in a textview and automatically scroll to the line of the word you are searching for...search widget is on the actionbar. ....there is no tutorial like this on youtube. thank you
How to make fragment transaction inside the onclick listener of button in list view.
when you create another layout to customize the list inside it make fragment as you want inside that layout
Great video. I am new to Android. Do you have any code that shows how to update the listview data in this demo for re-display?
Once you've updated your data source (eg. your array of strings) just call .notifyDataSetChanged() on your adapter
quite great explanation..Thanks.
i have a question..how about if i wanted to get listview area being click out..when should i put the listener?
+faeezstranger listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
String selected = ((TextView) view.findViewById(R.id.movie_name)).getText().toString();
Toast toast = Toast.makeText(getApplicationContext(),selected,Toast.LENGTH_LONG);
toast.show();
}
});
what do you mean by clicked out?
the item on list being click..
+faeezstranger I don't really understand your question. If you want to handle list clicks my video should show you how to do that. I have the source code on github also.
Sorry to wake up an old video, but why every Item on the list is called "New Text" and not like the generated data "This is like number 1..."? How would we go about doing this?
Nevermind found the answer in the comments :)
If I have two textviews, how can I set values in both? Thanks in advance!
If you store the references in viewholders like I've down with the imageview reference, just use that to set any views properties with appropriate casting where necessary.
+Jonathan Davis (iBlacklegend) i'm sorry i have the same question. i want to set, example, movie name and movie genre in 1 list item where both have there own textview. In generateListContent(), data.add can only pass 1 value for a text view. how can i pass 2 values for the separate textviews in data when data is an ArrayList of type string? sorry being a newb in advance....
+AbikersPOV Instead of a string, you can store a custom item called 'Movie' that has two fields that hold the movie' title and genre. Doing this will allow you to add additional data to the list item in the future if you wish to do so. Some examples would be adding the movie's rottentomato or metacritic score, the movies star rating aggregation, the movies runtime and watched/unwatched flag.
Give me source code button click to set ringtone in listview button added
Hi, i find helpful your video. Please can you explain me how to add different layout .xml? Thank you
In your project explorer right click on the layout folder and select the option "new > Layout Resource file".
He's a smart man not that I understand this stuff probably
i am not getting what is happening ..in the video and have seen 3,4 videos of similiar kind.Can anybody help..?
yes me too now this happening but when i set onclickleistener nothing happen
here the link use baseadapter ua-cam.com/video/tLVz5wmNyrw/v-deo.html
How can I change the Titles?
set a textview where you want then set a list in array using string then do like what this guy done
Hi,
How to pass the list item value to other activity.
Could you help me on this.
-thanks
Pacakge the value inside of a bundle using one of its various typed methods for storing a value and then store the bundle inside of the starting intent for the new activity.
ua-cam.com/video/2kUBcbUMDKE/v-deo.html
Thanks for the educational video. but can you slow a bit down? :/
my app crashes. please help.
hey Jonathan Davis. very very nice tutorial i wish u could help me out some problem, actually i'm Stuck in some kind of problem which is concerned with two clickable radio button on a listview ,when i scrolled the listview, then all the listview item position is changed as well as the radio button ,so MR. Jonathan could u do that to write this code ..
I don't see the problem you're having. Could you explain exactly what is happening when you scroll because all the listview item position is changed as well as the radio button isn't clear.
+Jonathan Davis (Wade)
firstly thanks to replying.. i'll tell the exact problem..
i have a listview and listview contains two radio button one is yes and other is no .. when I'm scrolling my listview and selecting my yes radio button then again I'm scrolling my listview then others radio buttons are automatically selclected ...thts the main problem
ATUL VARSHNEY The problem is that the views and their state (such as checked, selected, enabled, disabled etc) are being recycled when you scroll the ListView. You need to manually check whether whatever criteria you are use the radio button represents inside of every call to getView(),
GREAT TUTORIAL, VERY HELPFUL. I made a list of buttons, they couldnt fit all on the screen, but I cant scroll down to see the hidden buttons below, PLease how can I achieve that? Also tried making a vertical Linear Layout to implement it, but didn't work, I'll really apreciate how it can be done with a Linear Vertical Layout too.
I may be able to help you but just for clarities sake, could you draw a small image of exactly what you're trying to achieve?
Basically on the video, no activity launches when you press a button, so how can that be achieved(different buttons, different acitivities launched). Like example, when you fire up an SMS app, a list comes up with all your messages, and you can scroll from top to bottom, so how can i do that???
Inside of the views onClick method, do not start a new activity and just leave it blank if you don't want the view to react to clicks.
what IDE is that?
george gallimore Android Studio. I'm using a Material Design plug-in.
the activities are not so clear due to BLACK background.
Hey any idea why implementing your code is crashing my app on my mobile?
It can be any number of things. First check your log cat and see what line is causing the crash.
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
This is what i got in logcat.
on setAdapter function when pressed Alt+Enter suggests to assert lv!=null.
did you create a ListView variable somewhere? if not, then make one. if yes, then you are probably not filling the list with anything to show. you need to give the adapter an array of things (last argument of adapter creation) which the adapter should display in the ListView
Thank You Sir !! this helped me a lot (y)
but when i click on a button it doesn't show it's correct position !
+Vikrant Singh that's pretty much it (y) thanks for responding!!
+Vikrant Singh +Joe IsNotimpressed I updated the code on github that should fix the incorrect position issue.
Why you did not explain the code that already was in the application? ((((((((((((((
Hi. Where can we find source code? Thank you.
+MisterLoba Loba I haven't made the source code public. I can add it to github tomorrow.
this would be better if u used string-array values than generate with a fixed value with the same item name.
My video is fine as is, but since it so close to Christmas I'll be helpful. Only a simple change is needed to implement what you want.
Also using an ArrayList is a good example for the tutorial purpose of this video because it has a very simple interface that is common amongst other collection classes and can easily be switched out with minimum code rewriting.
Never show what activity_main. Xml contains...
In your project explorer right click on the layout folder and select the option "new > Layout Resource file".
Why do they all say "New Text"? Shouldn't they say whatever is in your data?
When the item scrolls off screen and then back on, it has the correct name. Just wondering why this is the case. Great tutorial btw.
There was a bug in my getview() method that caused it my logic to incorrectly choose the wrong indexes from the listview. The code on my GitHub should contain a solution.
so bad
we have 3 class in only one java file and we have two clickliner in two différentes classes ane one is in static we cannot call method is very bad
Not working for me
Please be more descriptive. What exactly isn't working for you? Are you getting exceptions or is nothing loading when you run the app?
When I run app it crashes.
I probably made mistake somewhere
What's the logs inside of your logcat when you run the app? Can you post your code to Github and I will take a look at it.
look jonathan github, maybe will be help
how to create listview with button click to another activity
hy bro
You have to slow down and explain everything. You talk too fast
talk just a little bit slower, you seemed breathing hard
This SUCKS! NO CODE EXPLANATION!
Crappy tutorial, cant even run my app ... i was trying to see detailed one, but u go over the code like we know all ... in the xml files u never mentioned how to create the list_item.xml or that shit, i was having problem with the activity_main.xml
content_list or some shit like that , i wasted like 30 minutes trying to figure it out how to do it ... never had succeed and... u never explain how to modifi a certain quanity of the things in the list ... it seems it autogenerate 6 or 10 items.. bad tut
+Armando Barreda You are complaining about a tutorial that doesn't fit to your use case. That is very unprofessional and uncalled for. I made this tutorial to be very generic and general purpose, as to teach anyone to implement an enhanced ListView. Your problem seems to be (besides being rude and disrespectful) centered on the fact you don't understand the basics of ListView, and the Android layout system. My video assumes a certain level knowledge to be able to achieve the enhanced ListView.
This tutorial was very helpful and beneficial even-though it was made years ago, if you dont understand code to a certain degree; dont run your mouth off to someone who has given his time in helping other people understand efficient ways in using list views. Cheers for the tutorial btw(forgot to mention it) :)
TheCheeky901 shut up kid
Armando Barreda well I can tell that you still can't code
@Hello, World maybe learn how to do the work on your own. You're criticizing a free tutorial because it doesn't give you all the work you need. As you said it would only take 30 seconds, why don't you make your own video that includes it an unnecessary snippet of making a basic list item. Secondly, I posted all of the code online, so you can just as easily go there and look at it. Of course, I'd be offended by both his and your disrespectful and entitled comments on a video I posted two years old for a class assignment.