This post will discuss how to add a ListView.
Create a New Application.
Go to Palette. Select the Composite section.
Drag ListView component on to the UI design.
Right click on the ListView dragged on the UI design.
Edit the ID. Give it the name lv_Items.
activity_show_list.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ShowListActivity" >
<ListView
android:id="@+id/lv_Items"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Add new XML file. See the following code:
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv_Item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black" />
</LinearLayout>
Go to Package Explorer --> Expand Project ListViewDemo --> Expand src --> Expand the package com.samples.listviewdemo
--> Open the ShowListActivity.java
package com.samples.listviewdemo;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ShowListActivity extends Activity {
// ListView to show the Items
private ListView lv_Items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_list);
// Initialize ListView
lv_Items = (ListView) findViewById(R.id.lv_Items);
lv_Items.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, R.id.tv_Item, getItems()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_show_list, menu);
return true;
}
private List<String> getItems() {
List<String> ls_Items = new ArrayList<String>();
try {
ls_Items.add("Apple");
ls_Items.add("Orange");
ls_Items.add("Mango");
} catch (Exception e) {
Log.e("getItems()", e.getMessage());
}
return ls_Items;
}
}
Run the application.
No comments:
Post a Comment