android studio通讯录代码和布局文件
时间: 2023-07-27 18:19:47 浏览: 120
以下是一个简单的 Android Studio 通讯录应用的代码和布局文件:
activity_main.xml:
```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="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/contact_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
```
contact_list_item.xml:
```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="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<TextView
android:id="@+id/contact_name_text_view"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/contact_phone_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp" />
</LinearLayout>
```
Contact.java:
```java
public class Contact {
private String mName;
private String mPhoneNumber;
public Contact(String name, String phoneNumber) {
mName = name;
mPhoneNumber = phoneNumber;
}
public String getName() {
return mName;
}
public String getPhoneNumber() {
return mPhoneNumber;
}
}
```
MainActivity.java:
```java
public class MainActivity extends AppCompatActivity {
private ListView mContactListView;
private ContactAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContactListView = (ListView) findViewById(R.id.contact_list_view);
ArrayList<Contact> contacts = new ArrayList<>();
contacts.add(new Contact("Alice", "123-456-7890"));
contacts.add(new Contact("Bob", "234-567-8901"));
contacts.add(new Contact("Charlie", "345-678-9012"));
mAdapter = new ContactAdapter(this, contacts);
mContactListView.setAdapter(mAdapter);
}
private class ContactAdapter extends ArrayAdapter<Contact> {
public ContactAdapter(Context context, ArrayList<Contact> contacts) {
super(context, 0, contacts);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.contact_list_item, parent, false);
}
Contact contact = getItem(position);
TextView nameTextView = (TextView) convertView.findViewById(R.id.contact_name_text_view);
nameTextView.setText(contact.getName());
TextView phoneTextView = (TextView) convertView.findViewById(R.id.contact_phone_text_view);
phoneTextView.setText(contact.getPhoneNumber());
return convertView;
}
}
}
```
这个应用程序只是简单地显示了一个联系人列表,每个列表项包含了联系人的姓名和电话号码。这个列表使用了自定义的列表项布局文件 `contact_list_item.xml` 和一个自定义的 `ContactAdapter` 类来显示数据。
阅读全文