Learn Android App Dev: Using ListView
Hey Guys! This is Amey Lokhande. In this post I'll be guiding you on how to use ListViews in your Android App.
Well, ListView is generally used when you have to choose any one option from a lot of options. ListView contains options populated in it. What I mean to say is, there can be multiple items present in a single ListView Container. And we can OnClickListener on that selected item according to our needs.
So here are the steps:
1. Create a new project.
2. In your Main_Activity.xml drag a ListView container.
3. Now right click on the layout and then choose New->XML->Layout XML file. Then you will get a new XML file. Give a appropriate name to that XML file.
4. Now that you have designed the layout of your App. Lets write the Java Code!
i) First of all, declare your ListView container in your Main_Activity.java. Also declare a string array which you will like to show in the ListView Container.
ii) Create a new function which will be used to show a Toast message on selecting a particular item from the ListView. So first we need to cast our ListView variable in that method.
iv) Now using a adapter we are going to feed all the data from the string array to the ListView. To use an Adapter create a new Adapter and give proper arguments in it as follows. Use 'Lv.setAdaapter(Adapter)' to set your string items into the ListView.
v) Now, create a new OnItemClickListener for the items clicked from the List. Using this method we will show a Toast message for the Item which is selected.
vi) Thats all! Here's a screenshot of the working app:
Java Code:
package com.example.ameylokhande.lists;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast;
public class MainActivity extends AppCompatActivity { private static ListView lv; private static String[] cities =new String[]{"Nagpur","Pune","Ahmedabad","Goa","Delhi"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); my_list(); } public void my_list(){ lv = (ListView)findViewById(R.id.list_v); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_of_cities,cities); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this,position+"\n"+cities[position],Toast.LENGTH_LONG).show(); } }); } }
So this is it! Thanks for reading!
Stay tuned for further updates!