We provide complete mobile and web apps development solutions

Thursday, July 26, 2012

ListView in Android

We can create listview in two ways.


1. The activity extending from ListActivity

 

 MainActivity  extend ListActivity

public class MainActivity extends ListActivity {
...
}

 

public class ListAct extends ListActivity {
  TextView selection;
  private static final String[] items={"Apple", "Bat", "Cat",
          "Dog", "Eagle",
          "Fan", "Goat", "Hut", "Iron", "Jackel",
          "Kitten", "Lion", "Mat", "Nut"};
 
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    setListAdapter(new IconicAdapter());
    selection=(TextView)findViewById(R.id.selection);
  }
 
  public void onListItemClick(ListView parent, View v,
                              int position, long id) {
    selection.setText(items[position]);
  }
 

Create  the list adapter
//list of array strings which will serve  as LIST ITEMS
 

  class IconicAdapter extends ArrayAdapter<String> {
    IconicAdapter() {
      super(ListAct.this, R.layout.row, R.id.label, items);
    }
   
    public View getView(int position, View convertView,
                        ViewGroup parent) {
      View row=super.getView(position, convertView, parent);
      ImageView icon=(ImageView)row.findViewById(R.id.icon);
       
      if (items[position].length()>4) {
        icon.setImageResource(R.drawable.remove);
      }
      else {
        icon.setImageResource(R.drawable.Yes);
      }
     
      return(row);
    }
  }
}
 

main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
  <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
    />
</LinearLayout>
 

 row.xml

 

<?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"
>
  <ImageView
    android:id="@+id/icon"
    android:padding="2dip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/yes"
  />
  <TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="40sp"
  />
</LinearLayout>
 

2.extends from Activity

 

public class Example extends Activity {

    private List<Example> exampleList= new ArrayList<Example>();
    private List<String> list;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        // Set the View layer
        setContentView(R.layout.listview);
        setTitle("ExampleListView");
       
     

       
           
       
    

        // Create Parser for raw/example.xml
        ExampleParser exampleParser = new ExampleParser();
       
     
           
                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(directory.getPath()+
                             "/example.xml");
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
           
        InputStream inputStream = getResources().openRawResource(
                R.raw.example);       
       
        // Parse the inputstream
        countryParser.parse(inputStream);

        // Get Countries
        List<Country> exampleList = exampleParser.getList();
       
       
        // Create a customized ArrayAdapter
        ExampleArrayAdapter adapter = new ExampleArrayAdapter(
                getApplicationContext(), R.layout.example_listitem, exampleList);
       
        // Get reference to ListView holder
        ListView lv = (ListView) this.findViewById(R.id.exampleLV);
       
        // Set the ListView adapter
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                /*
                Object fruit=this.getListAdapter().getItem(position);
                Object fruitid=this.getListAdapter().getItemId(position);*/
                 addItem(arg1);
            }

            public void addItem(View v) {
                // TODO Auto-generated method stub
                try{
                    LinearLayout layout = (LinearLayout) v;
                String name_example = ((TextView) layout.findViewById(R.id.name_example)).getText()
                        + "";
                String example_abbrev = ((TextView) layout.findViewById(R.id.example_abbrev))
                        .getText() + "";
               
               

               

                try {
                    showItem(name_example, example_abbrev);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                }catch(Exception e){}
               
            }

            public void showItem(String name_example, String example_abbrev) {
                // TODO Auto-generated method stub
                try {
                Intent in= new Intent(ExampleAct.this,ItemDetails.class);
               
                   
                    //Intent in = new Intent(this, ItemDetails.class);
                    //Intent in= new Intent(this,ItemDetails.class);
                    //Intent in = new Intent(this, ItemDetails.class);
                   
                  startActivity(in);
                   
                } catch (Exception e) {
                    GpsLogs.ExceptionLog("Ex " + e);
                }   
            }
        });
            }  }
   
    in raw
    example.xml

<?xml version="1.0" encoding="utf-8"?>
<example>
        <name name="Ameerpet" abbreviation="au" region="Ap" />
        <name name="Begumpet" abbreviation="at" region="Hyderabad" />
        <name name="Chikkadapalli" abbreviation="be" region="Hyderabad" />
        <name name="Dabirpura" abbreviation="br" region="Secbad" />
        <name name="Ecil" abbreviation="ca" region="Secbad" />
        <name name="Falaknuma" abbreviation="cn" region="Hyderabad" />
        <name name="Gunfoundry" abbreviation="dk" region="Europe" />
        <name name="Hayat nagar" abbreviation="fr" region="Europe" />
        <name name="India" abbreviation="de" region="Europe" />
        <name name="Jammu" abbreviation="hk" region="Asia" />
        <name name="Kurnool" abbreviation="in" region="Asia" />
        <name name="Lucknow" abbreviation="id" region="Asia" />
        <name name="masabtank" abbreviation="it" region="Europe" />
        <name name="Noida" abbreviation="kr" region="Asia" />
        <name name="Ongole" abbreviation="nl" region="Europe" />
        <name name="Parchur" abbreviation="no" region="Europe" />
        <name name="Quthbullapur" abbreviation="pt" region="Europe" />
        <name name="Raipur" abbreviation="sg" region="Asia" />
        <name name="Shamlal" abbreviation="es" region="Europe" />
        <name name="Timmapur" abbreviation="se" region="Europe" />
        <name name="Usa" abbreviation="ch" region="Europe" />
       
        <name name="Others" abbreviation="uk" region="Europe" />
        <name name="Other cities" abbreviation="us" region="N. America" />
</example>


  Listview item repeating 50 times with increasing order


public class MainActivity extends Activity
{
    private ListView myList;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        
        ArrayList<String> list = new ArrayList<String>();
 // 50 times repeat
        for (int i = 0; i < 50; i++){
            list.add("Blog" + i);
        }

        myList = (ListView)findViewById(R.id.list);

      
      
 
        myList.setAdapter(new MyCustomAdapter(MainActivity.this,list));


    }
}


public class MyCustomAdapter  extends BaseAdapter {
    private ArrayList<String> mListItems;
    private LayoutInflater mLayoutInflater;

    public MyCustomAdapter(Context context, ArrayList<String> arrayList){

        mListItems = arrayList;

        //get the layout inflater
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        //getCount() represents how many items are in the list
        return mListItems.size();
    }

   
        //get the data of an item from a specific position
        //i represents the position of the item in the list
    public Object getItem(int i) {
        return null;
    }

   
        //get the position id of the item from the list
    public long getItemId(int i) {
        return 0;
    }

    public View getView(int position, View view, ViewGroup viewGroup) {

        //check to see if the reused view is null or not, if is not null then reuse it
        if (view == null) {
            view = mLayoutInflater.inflate(R.layout.list_item, null);
        }

        //get the string item from the position "position" from array list to put it on the TextView
        String stringItem = mListItems.get(position);
        if (stringItem != null) {

            TextView itemName = (TextView) view.findViewById(R.id.list_item_text_view);

            if (itemName != null) {
                //set the item name on the TextView
                itemName.setText(stringItem);
            }
        }

        return view;

    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <ListView android:id="@+id/list"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:transcriptMode="alwaysScroll"
              android:cacheColorHint="#00000000"
              android:listSelector="@android:color/transparent"/>
</LinearLayout>

list_item.xml


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/list_item"
        android:gravity="center_vertical">


    <TextView android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/list_item_text_view"
              android:textSize="20sp"
              android:padding="10dp"
              android:layout_marginLeft="5dp"/>

</LinearLayout>



0 coment�rios:

Post a Comment

Online Training

Your Name :
Your Email: (required)
Your Message: (required)

Blog Archive

Powered by Blogger.

Recent Posts

Find Us On Facebook

Popular Posts