Sunday, November 16, 2014

Customize ListItem using Simple Array Adapter

Hi all,

      Today I am  going to discuss that how to customize list item little bit by using simple Array Adapter.
Please follow the steps:

1. MainActivity.java class.

  package abc.esc.list;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ListCustActivity extends Activity {
    /** Called when the activity is first created. */
    ListView list;
    ArrayAdapter<String> adapter;
    String[] arr={"Android", "Windows","Linux","iOS","Mac","Unix"};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        list=(ListView)findViewById(R.id.listView1);
       
        adapter= new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, arr);
       
        list.setAdapter(adapter);
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Item clicked "+arg2, 344).show();
            }
        });
       
    }


       

2. activity_main.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="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >


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

</LinearLayout>



3. list_item.xml.

 
   
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:textColor="#DF0101"
        android:text="TextView" />











4. Output:




 

   Note: There is no change in manifest.xml.

Thanks!!!!!