Saturday, August 1, 2015

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 com.smr; //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 implementsOnItemClickListener
{
      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_1values);
            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();
           
      }
}

No comments:

Post a Comment