Wednesday, 3 April 2013

What is Listview in android and how to work with android Listview ?

Android provides the ListView class which is capable of displaying a scrollable list of items. These items can be of any type.

 Now lets take one example of ListView. We can understand ListView step by step.

 Step 1 :- Create one project give it name ListViewDemo. now in main.xml file we take one ListView like following.

  main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="Android Advance Listview Demo"
        android:textColor="#ff9966"
        android:textSize="20dp"
        android:text />
    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>

 step 2 :- Now we create one java file which items in a list and handle events.

 ListVIewDemoActivity.java

  public class ListVIewDemoActivity extends Activity implements OnClickListener {
    ListView listview;   
    ArrayList<String> listviewitems = new ArrayList<String>();

    // listviewitems is array which display items in a list

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Now get id of ListView 
        listview = (ListView) findViewById(R.id.listview);
         
    }
  @Override
    protected void onResume() {
        super.onResume();
    
        we need to clear listviewitems every time becase when this activity resumes it add elements to the list so first clear listview and after we add elements to listviewitems.

        listviewitems.clear();
        listviewitems.add("Animals");
        listviewitems.add("Birds");
        listviewitems.add("Fruits");
        listviewitems.add("Computer Parts");
        listviewitems.add("Electronic Products");

    A ListView receives its data via an adapter. The adapter also defines how each row is the ListView is displayed.  The adapter is assigned to the list via the setAdapter method on the ListView object.   An adapter extend the BaseAdapter class. Android provides several standard adapters; the most important are ArrayAdapter and CursorAdapter. Here we use BaseAdapter.

        listview.setAdapter(new ListAdapter(this, this));
    }

  Now we have to create our own ListAdapter for listview adapter.

  private class ListAdapter extends BaseAdapter {
        LayoutInflater inflater;

       we have to create one inner class ViewHolder for storing child views.
        ViewHolder viewHolder;
        Activity activity;


      constructor of ListAdapter
    public ListAdapter(Context context, Activity act) {
            inflater = LayoutInflater.from(context);
            this.activity = act;
        }


   getCount() display total numbers of items in a list
  public int getCount() {
            return listviewitems.size();
        }

  public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView,
                ViewGroup parent) {
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.list_row, null);
                viewHolder = new ViewHolder();

                viewHolder.pname = (TextView) convertView
                        .findViewById(R.id.txtname);

                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.pname.setText(listviewitems.get(position));

        To react to selections in the list set an OnItemClickListener to your ListView.

            convertView.setOnClickListener(new OnItemClickListener(position));
            return convertView;

        }
    }
  Within the getView() method you would inflate an XML based layout and then set the values of the individual Views in the layout. For inflating an XML layout you can use the system service LayoutInflator. This service can get accessed via the Activity or via the context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) method call.

  private class ViewHolder {
        TextView pname;
    }

  Now we create our own listener for the listview item click.

  private class OnItemClickListener implements OnClickListener {
        private int mPosition;

        OnItemClickListener(int position) {
            mPosition = position;
        }

        public void onClick(View v) {

            Toast.makeText(ListVIewDemoActivity.this,
                    "" + listviewitems.get(mPosition), Toast.LENGTH_LONG)
                    .show();

      we pass position which is clicked in listview to next activity by passing intent to ListItemDetail.java.
            Intent i = new Intent(ListVIewDemoActivity.this,
                    ListItemDetail.class);
            i.putExtra("position", "" + mPosition);
            startActivity(i);
        }

    }
  step 3 :-  we need to create list_row.xml file for list row display so create new xml file like following.

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/txtname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="20dp"
            android:text="Product Name"
            android:textColor="#FF9900"
            android:textSize="22dp"
            android:text />
    </LinearLayout>
</LinearLayout>

  Step 4 :- Now for dispay item which is clicked we have to create new class name it to ListItemDetail.java. We display image corresponding to item click on listview so create one xml file which display image.


  listitemdetail.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

  ListItemDetail.java
   public class ListItemDetail extends Activity {
    
       we get position and store it to variable.
      int position;
      ImageView image;
     
    int[] images = { R.drawable.animals, R.drawable.birds, R.drawable.fruits,
            R.drawable.pcparts, R.drawable.electronics };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listitemdetail);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {

              now get position which is passed from first activity. Here we pass from first activity using putExtra() so we must covert it in integer by using Integer.valueOf() method by using following.

            position = Integer.valueOf(extras.getString("position"));
            image = (ImageView) findViewById(R.id.imageview);

            We set image on imageview by using  setBackgroundResource() method.
            image.setBackgroundResource(images[position]);
        }
    }
}


2 comments:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    ReplyDelete
  2. I have read your blog its very attractive and impressive. I like it your blog.

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete