Featured post

Displaying Multiple Fragments in a single Activity

Thursday, 21 July 2016

ListView in Android Applications

In this tutorial, i am going to show you how to group lot of items and put it in a list in your application. To achieve this, i am going to use the class ListView in android which extends
(AbsListView). 

Let's us start with a simple example of ListView.
1. Create a new android application.
2. You will end with two files, one is the activity_main and the other one is the MainActivity( which is by default naming convention).
3. Write the below code


activity_main.xml coding
---------
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="">

<TextView
android:id="@+id/textView1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Cars" />

<ListView
android:id="@+id/listView"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>

</LinearLayout>
-----------------
MainActivity.java Code:


public class MainActivity extends Activity
{
ListView list;
String [] cars={"Cabrio","Capri","Brava","Brat","Boxter","Camry"};
ArrayAdapter<String> mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView)findViewById(R.id.listView);
mAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,cars);
list.setAdapter(mAdapter);
}
}

output:


No comments:

Post a Comment