In this Listview example, we display a list of countries by using simple array adapter. Below is the final output we will create:
Step 1: Create a new project Listexample and activity Main Activity. Here we will create a ListView in LinearLayout. Below is the code of activity_main.xml or content_main.xml:<?xml version="1.0" encoding="utf-8"?>Step 2: Create a new activity name Listview and below is the code of activity_listview.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/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="@color/material_blue_grey_800"
android:dividerHeight="1dp" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>Step 3: Now in this final step we will use ArrayAdapter to display the country names in UI. Below is the code of MainActivity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="@dimen/activity_horizontal_margin"
android:textColor="@color/black" />
</LinearLayout>
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;import android.widget.ListView;
public class MainActivity extends Activity
{
// Array of strings...
ListView simpleList;
String countryList[] = {"India", "China", "australia", "Portugle", "America", "NewZealand"};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
simpleList = (ListView)findViewById(R.id.simpleListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_listview, R.id.textView, countryList);
simpleList.setAdapter(arrayAdapter);
}
}
No comments:
Post a Comment