英文:
Get Chip Text on click chip
问题
我是Android的新手,正在尝试使用芯片(Chips)功能。我在XML中有一个类似这样的芯片组(ChipGroup):
<com.google.android.material.chip.ChipGroup
android:padding="10dp"
android:id="@+id/tags"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:chipSpacing="10dp">
</com.google.android.material.chip.ChipGroup>
我正在动态地向其中添加芯片,像这样:
Chip chip = new Chip(getLayoutInflater().getContext());
for (String genre : tags_text) {
chip.setText(genre);
tags.addView(chip);
}
添加芯片的功能正常。现在我想要获取点击芯片的文本内容。我尝试像这样获取:
chip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int chipsCount = tags.getChildCount();
String TagText = "";
int i = 0;
while (i < chipsCount) {
Chip chip = (Chip) tags.getChildAt(i);
if (chip.isChecked()) {
TagText = chip.getText().toString();
}
i++;
}
Log.e("CHIPS", TagText + "-OK");
}
});
但是我总是得到空白的文本。如果有人可以帮助我解决这个问题,请告诉我。谢谢!
英文:
I am new to android and trying to play with chips. I have chip group like this in xml
<com.google.android.material.chip.ChipGroup
android:padding="10dp"
android:id="@+id/tags"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:chipSpacing="10dp">
</com.google.android.material.chip.ChipGroup>
I am dynamically adding chip like this in it.
Chip chip = new Chip(getLayoutInflater().getContext());
for(String genre : tags_text) {
chip.setText(genre);
tags.addView(chip);
}
Adding chip is working fine. Now I want get chip text of clicked chip. I am trying to get it like this
chip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int chipsCount = tags.getChildCount();
String TagText ="";
int i = 0;
while (i < chipsCount) {
Chip chip = (Chip) tags.getChildAt(i);
if (chip.isChecked() ) {
TagText = chip.getText().toString();
}
i++;
};
Log.e("CHIPS", TagText+"-OK");
}
});
But I am getting empty text always. let me know if someone can help me for solve it.
Thanks!
答案1
得分: 0
可以使用:
chip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = ((Chip) view).getText().toString();
//...
}
});
英文:
You can use:
chip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = ((Chip) view).getText().toString();
//...
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论