1. Modify the layout file:
<?xml version="1.0"encoding="Utf-8"?><linearlayoutXmlns: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"Android:paddingbottom="@dimen/activity_vertical_margin"Android:paddingleft="@dimen/activity_horizontal_margin"Android:paddingright="@dimen/activity_horizontal_margin"Android:paddingtop="@dimen/activity_vertical_margin"android:orientation= "Vertical"Tools:context="com.example.chuny.ch10listview.MainActivity"> <TextView android:layout_width="wrap_content"Android:layout_height="wrap_content"Android:text="Hello world!"/><listview android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:id= "@+id/listview" ></ListView></LinearLayout>
2. Modify the Java file:
3. Operating effect:
4. Three types of adapters are introduced:
(1) How to read the phone Address Book information: Read data
PrivateList<string>Getcontactname () {List<String> contacts=NewArraylist<> ();//list<string> Specifies that the type of List can only be a String//Define a content parser, which is a content parser that is required to read the resources of the mobile system .Contentresolver cr=Getcontentresolver (); //get the address of a mobile phone recordCursor Cursor=cr.query (ContactsContract.Contacts.CONTENT_URI,NULL,NULL,NULL,NULL);//define a cursor//loop through contacts inside contacts if(Cursor.movetofirst ()) { Do{String name=cursor.getstring (Cursor.getcolumnindex (ContactsContract.Contacts.DISPLAY_NAME));//cursor types are converted to data types//read the contact name in the mobile phone recordContacts.add (name); } while(Cursor.movetonext ()); } cursor.close (); //close cursor, cursor-like pointer, when reading database returncontacts; }
Define the adapter:
protected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); ListView=(ListView) Findviewbyid (R.id.listview); //arrayadapter<string> adapter=new arrayadapter<string> (mainactivity.this,r.layout.support_simple_ Spinner_dropdown_item,datasource); //Listview.setadapter (adapter); arrayadapter<string> adapter=new arrayadapter<string> (mainactivity.this , R.layout.support_simple_spinner_dropdown_item,getcontactname ()); Listview.setadapter (adapter); }
Error:
Modify Permissions:
Operating effect:
(2)
2017.12.4 Android Developer's ListView component