【发布时间】:2021-07-24 11:33:02
【问题描述】:
我想制作一个文本框,用户可以在其中输入逗号 (, ) 来分隔 这个单词。这基本上称为标签
为了更好理解,我举个例子-
当你在 StackOverflow 中提问时,你必须输入标签
我说的是那些标签
【问题讨论】:
我想制作一个文本框,用户可以在其中输入逗号 (, ) 来分隔 这个单词。这基本上称为标签
为了更好理解,我举个例子-
当你在 StackOverflow 中提问时,你必须输入标签
我说的是那些标签
【问题讨论】:
你必须使用筹码
确保存储库部分包含 Google 的 Maven 存储库 google()。例如:
allprojects {
repositories {
google()
jcenter()
}
}
将库添加到依赖项部分:
dependencies {
// ...
implementation 'com.google.android.material:material:<version>'
// ...
}
然后在您的 xml 代码中使用此代码
<com.google.android.material.chip.Chip
android:id="@+id/chip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text"/>
你可以从java部分访问它
chip.setOnClickListener {
// Responds to chip click
}
chip.setOnCloseIconClickListener {
// Responds to chip's close icon click if one is present
}
chip.setOnCheckedChangeListener { chip, isChecked ->
// Responds to chip checked/unchecked
}
您也可以将芯片组用于动态芯片
<com.google.android.material.chip.ChipGroup
android:id="@+id/chipGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- Chips can be declared here, or added dynamically. -->
</com.google.android.material.chip.ChipGroup>
希望我的回答有用
如果你想用逗号添加新项目,你必须使用chipgroup并创建textwatcher,并在每次更改edittext时添加逗号之间的项目以列出并刷新chipgroup
更新部分
你可以像这样创建文本观察器,然后用逗号分隔java.lang
yourEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
// s is your string in edittext
// create an arraylist
// use .splite by ","
// put result in array list
// update your chipgroup by arraylist
//if it was useful set answer as correct
}
});
【讨论】:
Arrays.asList 返回一个由数组支持的固定大小的列表。如果你想要一个普通的可变 java.util.ArrayList 你需要这样做:
List list = new ArrayList(Arrays.asList(string.split(" , ")));
或者,使用番石榴:
List list = Lists.newArrayList(Splitter.on(" , ").split(string));
使用拆分器可以让您更灵活地拆分字符串,并让您能够跳过结果中的空字符串并修剪结果。与 String.split 相比,它的怪异行为更少,并且不需要您按正则表达式进行拆分(这只是一种选择)。
【讨论】: