Insert ListView in Android App

ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list.

XML file


<?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"
      >
   <ListView
       android:id="@+id/att_listView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
     >
     </ListView>       
  </LinearLayout>

Java FIle    


import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
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 Listview extends Activity {

ListView listview;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);

//Initialize ListView
listview=(ListView)findViewById(R.id.att_listView);
//ADd Items in List View
ArrayList<String> list=new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
list.add("other Fruits");

//Bind list View to Array Adapter to List and Default list View
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,list);
//set Adapter to ListView
listview.setAdapter(adapter);
//ListView onClick Listener
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View arg1, int position,long id)
{
// what ever you want to perform
String item=String.valueOf(adapter.getItemAtPosition(position));
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_SHORT).show();
}
});
}
}

Output

0 comments:

Post a Comment