Search Tutorials

Monday 7 October 2013

How to create a list and perform action in Android

Just drop listview widget in layout and give id listView1 or paste this code in main xml file:

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

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

</LinearLayout>


Now open your Java file and paste below code
 

package sel.listG; //package name

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;
import android.app.Activity;

public class MainActivity extends Activity implements OnItemClickListener
{
      String values[]={"January", "July", "June", "Ravi", "Ravinder", "Abhishek", "Abhinav", "Harkishore", "Hardev"};

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ListView lv=(ListView)findViewById(R.id.listView1); 
//Adapter will use to adapt string and pass to list 
            ArrayAdapter<?> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
            lv.setAdapter(adapter);
            lv.setOnItemClickListener(this);
                
      }

      @Override
      public void onItemClick(AdapterView<?> av, View v, int pos, long id)
      {
            String name=(String)av.getItemAtPosition(pos);
            Toast.makeText(getApplicationContext(), "Happy Navratri "+name, Toast.LENGTH_SHORT).show();
           
      }
}


Now run code...

6 comments:

  1. Thanks for the tutorial. Can you please share screenshot of the final output which eases the understanding.

    ReplyDelete
    Replies
    1. sure but you to wait for that because i am going to re-write all post that's why it may take time.

      Delete
  2. Please share .php files related to this project

    ReplyDelete
  3. guys i need help i have this project which i have to create "ONLINE GIFT REGISTRY" in java on eclipse....and i dont have much time anyone who can help please EMAIL ME::thatosramoshaba@gmail.com

    ReplyDelete
  4. can you please give me output screen shot

    ReplyDelete
  5. Hi all,
    Can any one share how to pass the images dynamically through intent to another activity's imageview using image position in custom listview.?

    ReplyDelete

Back to Top