ListView in Android
ListView is used to show the list of data with vertically scrolling . This example helps you to create a ListView in android. The items are automatically inserted in 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.
Step 1: Create Project
a) Open Android Studio
b) Go to File >New> New Project > Project Name > Next > Next > Next > Finish
Step 2 : Layout Design
open activity_main.xml file and add the bellow code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff33b5e5">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
Step 3 : Code
open MainActivity class and add the bellow code
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Created by anupam on 30/9/16.
*/
public class MainActivity extends Activity{
Context context;
ListView listView;
String[] names = new String[] { "Anupam Singh",
"Amit Datta",
"Parna Majumder",
"Soumita Hazra",
"Ajay Shaw",
"Sujan Dutta",
"Santu",
"Koushik Mondal "
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize context
context=this;
listView=(ListView)findViewById(R.id.list);
// Define a new Adapter
// First parameter - Context
// Second parameter - resource id
// Third parameter - textview resource id
// Forth - Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, names);
// set adapter to listview
listView.setAdapter(adapter);
// get the name on click of listview
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name=(String) listView.getItemAtPosition(position);
Toast.makeText(context,name,Toast.LENGTH_LONG).show();
}
});
}
}
Find Us :
Facebook : @apnaandroid
Google+ : Apna Java
Youtube : Android & Java Tutorial
Comments
Post a Comment