Thursday 15 October 2015

Android Custom ListView with SimpleAdapter – creating a table in android using listview

       Most of your application will be having a table or a table model listview. With the availability of a simple adapter you could achieve it in a simple manner. This tutorial will guide you to create a well arranged tabular listview with the help of a simpleAdapter for you android application.
.

Java:
        *Add the below code to your activity class; and call it to update the list view
public void LoadData() {  
     ListView listview1;  
     ArrayList arraylist = new ArrayList();  
     arraylist.clear();  
     listview1 = (ListView) findViewById(R.id.listview1);  
     HashMap<String, String> country;  
         For(intx=0;x<10;x++){  
             String title = cursor.getString(4);  
             String desc = cursor.getString(3);  
             String value = cursor.getString(2);  
             country = new HashMap<String, String>();  
             country.put("title", title);  
             country.put("desc", desc);  
             country.put("value", value);  
             arraylist.add(country);  
                     }  
     listview1.setAdapter(new SimpleAdapter(this, arraylist, R.layout. custom_row.xml, new String[] { "title", "desc","value” }, new int[] { R.id.title, R.id.desc, R.id.value }));  
     }  
       
XML:
        *create a custom_row.xml in layout directory and copy past the below code. This layout contains the custom resources to hold the values.

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="wrap_content"  
   android:orientation="horizontal"  
   android:paddingBottom="6.0dip"  
   android:paddingTop="4.0dip" >  
   <TextView  
     android:id="@+id/title"  
     android:layout_width="36dp"  
     android:layout_height="wrap_content"  
     android:text="title"  
     android:textSize="17dp" />  
   <TextView  
     android:id="@+id/desc"  
     android:layout_width="81dp"  
     android:layout_height="wrap_content"  
     android:layout_marginLeft="5dp"  
     android:text="desc"  
     android:textSize="17dp" />  
   <TextView  
     android:id="@+id/value"  
     android:layout_width="70dp"  
     android:layout_height="wrap_content"  
     android:layout_marginLeft="3dp"  
     android:text="value"  
     android:textSize="17dp" />  
 </LinearLayout>  


         * And finally add a listview to your activity layout file. copy past the below code to you layout xml file.
 <ListView  
     android:id="@+id/listview1"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content" >  

No comments:

Post a Comment