要实现Android联系人视图样式,可以使用RecyclerView和自定义Adapter来展示联系人列表。以下是一个基本的示例代码:
public class Contact {
private String name;
private String phoneNumber;
public Contact(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
}
public class ContactsAdapter extends RecyclerView.Adapter {
private List contacts;
public ContactsAdapter(List contacts) {
this.contacts = contacts;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView nameTextView;
public TextView phoneNumberTextView;
public ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.nameTextView);
phoneNumberTextView = itemView.findViewById(R.id.phoneNumberTextView);
}
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// 使用自定义的联系人布局文件
View contactView = inflater.inflate(R.layout.item_contact, parent, false);
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Contact contact = contacts.get(position);
TextView nameTextView = holder.nameTextView;
nameTextView.setText(contact.getName());
TextView phoneNumberTextView = holder.phoneNumberTextView;
phoneNumberTextView.setText(contact.getPhoneNumber());
}
@Override
public int getItemCount() {
return contacts.size();
}
}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ContactsAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
// 创建联系人列表数据
List contacts = new ArrayList<>();
contacts.add(new Contact("John Doe", "1234567890"));
contacts.add(new Contact("Jane Smith", "0987654321"));
// 创建适配器
adapter = new ContactsAdapter(contacts);
// 设置布局管理器和适配器
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
这样就可以实现一个简单的Android联系人视图样式了。你可以根据需求自定义联系人布局文件item_contact.xml,添加更多联系人信息等。