如果您正在寻找收件人编辑框,就像 Gmail 联系人编辑框一样,这里有一个可以帮助您的实施视频:
如何使用 Android 的 AutoCompleteTextView 实现芯片
假设您有一个联系人数据类,请执行以下操作:
MultiAutoCompleteTextView 设置
MultiAutoCompleteTextView contactAutoCompleteTextView = findViewById(R.id.recipient_auto_complete_text_view);
List<Contact> contacts = new ArrayList<Contact>() {{
add(new Contact("Adam Ford", R.drawable.adam_ford));
add(new Contact("Adele McCormick", R.drawable.adele_mccormick));
add(new Contact("Alexandra Hollander", R.drawable.alexandra_hollander));
add(new Contact("Alice Paul", R.drawable.alice_paul));
add(new Contact("Arthur Roch", R.drawable.arthur_roch));
}};
contactAutoCompleteTextView.setAdapter(new ContactAdapter(this,
R.layout.contact_layout, contacts));
contactAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
// Minimum number of characters the user has to type before the drop-down list is shown
contactAutoCompleteTextView.setThreshold(1);
contactAutoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Contact selectedContact = (Contact) adapterView.getItemAtPosition(i);
createRecipientChip(selectedContact);
}
});
芯片资源
<chip style="@style/Widget.MaterialComponents.Chip.Action"/>
芯片创建
private void createRecipientChip(Contact selectedContact) {
ChipDrawable chip = ChipDrawable.createFromResource(this, R.xml.standalone_chip);
CenteredImageSpan span = new CenteredImageSpan(chip, 40f, 40f);
int cursorPosition = contactAutoCompleteTextView.getSelectionStart();
int spanLength = selectedContact.getName().length() + 2;
Editable text = contactAutoCompleteTextView.getText();
chip.setChipIcon(ContextCompat.getDrawable(MainActivity.this,
selectedContact.getAvatarResource()));
chip.setText(selectedContact.getName());
chip.setBounds(0, 0, chip.getIntrinsicWidth(), chip.getIntrinsicHeight());
text.setSpan(span, cursorPosition - spanLength, cursorPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
CenteredImageSpan 是一个自定义 ImageSpan ,它垂直居中可绘制对象。它还允许我们设置芯片填充。完整的代码在链接中提供。
在此示例中,可以在您键入时从建议列表中选择联系人。然后,创建联系人芯片(带有名称和头像)来替换搜索查询。至于多个联系人处理,您正在寻找 MultiAutoCompleteTextView。视频中对此进行了描述。
希望能帮助到你。