main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
MainActivity.xml
public class MainActivity extends Activity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
// Defined Array
values to show in ListView
String[] values = new String[] { "Item
1", "Item 2", "Item 3",
"Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9",
"Item 10" };
// Define a new
Adapter
// First parameter -
Context
// Second parameter -
Layout for the row
// Third parameter -
ID of the TextView to which the data is written
// Forth - the Array
of data
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to
ListView
listView.setAdapter(adapter);
// ListView Item Click
Listener
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item value
String item =
(String) listView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position :" + position + " ListItem : " + item,
Toast.LENGTH_LONG).show();
}
});
}