activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="iterator.ir.a013.MainActivity"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:id="@+id/listViewCountries" /> </RelativeLayout>
listview_custom_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:text="TextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textViewListItem" android:gravity="center" android:textSize="18dp" android:textColor="@color/w3_highway_blue" android:paddingBottom="5dp"/> </LinearLayout>
res/values/strings.xml
<resources> <string name="app_name">013</string> <string-array name="countries"> <item>Iran</item> <item>Iraq</item> <item>India</item> <item>Italy</item> <item>Brazil</item> <item>France</item> <item>United Kingdom</item> <item>Pakistan</item> <item>Oman</item> </string-array> </resources>
MainActivity.java
ListView listViewCountries; ArrayAdapter<String> arrayAdapter; String[] countries; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); countries=getResources().getStringArray(R.array.countries); listViewCountries= (ListView) findViewById(R.id.listViewCountries); arrayAdapter=new ArrayAdapter<String>(this, R.layout.listview_custom_layout, R.id.textViewListItem,countries); listViewCountries.setAdapter(arrayAdapter); listViewCountries.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast toast=Toast.makeText(getBaseContext(),parent.getItemAtPosition(position).toString(),Toast.LENGTH_LONG); toast.show(); } }); }
References
https://github.com/mhdr/AndroidSamples/tree/master/013