问题是我无法删除“,”,而只检查了一项,并且当有多个项目时,我不知道如何从末尾删除“,”。
公共(public)类 CheckBox 扩展 AppCompatActivity 实现 View.OnClickListener {
ImageButton check_button;
CheckBox eminem , dre , tupac , royce , logic , big_sean;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_e10_check_box);
setTitle("Check Box");
Inits();
}
private void Inits(){
check_button = findViewById(R.id.check_button);
eminem = findViewById(R.id.eminem);
dre = findViewById(R.id.dre);
tupac = findViewById(R.id.tupac);
royce = findViewById(R.id.royca);
logic = findViewById(R.id.logic);
big_sean = findViewById(R.id.big_sean);
check_button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
String result = "Your Favorite List : x";
String singers = "";
if(eminem.isChecked()){
singers += "Eminem" + " , " ;
}
if (dre.isChecked()){
singers += "Dr.Dre" + " , ";
}
if (tupac.isChecked()){
singers += "Tupac" + " , ";
}
if (royce.isChecked()){
singers += "Royce" + " , ";
}
if (logic.isChecked()){
singers += "Logic" + " , ";
}
if (big_sean.isChecked()){
singers += "Big Sean" + " , ";
}
app.t(result.replace("x" , singers));
}
}
最佳答案
您可以尝试使用StringBuilder
以获得更好的性能。附加到它时不会创建新对象。以下是您的问题的可能解决方案:
StringBuilder builder = new StringBuilder();
if(eminem.isChecked()){
builder.append("Eminem").append(RAPPER_SEPARATOR);
}
if (dre.isChecked()){
builder.append("Dre").append(RAPPER_SEPARATOR);
}
if (tupac.isChecked()){
builder.append("Tupac").append(RAPPER_SEPARATOR);
}
if (royce.isChecked()){
builder.append("Royce").append(RAPPER_SEPARATOR);
}
if (logic.isChecked()){
builder.append("Logic").append(RAPPER_SEPARATOR);
}
if (big_sean.isChecked()){
builder.append("Big Sean").append(RAPPER_SEPARATOR);
}
final int length = builder.length();
if (length > 0) {
builder.delete(length - RAPPER_SEPARATOR.length() - 1, length - 1);
app.t(result.replace("x" , builder.toString()));
}
其中RAPPER_SEPARATOR = ", "
。
还要记住,代码有重复项,如果 CheckBox
文本与您要附加的文本相同,您可以创建一个函数来执行此操作,如下所示:
private void appendRapperIfChecked(CheckBox cb, StringBuilder builder) {
if (cb.isChecked()) {
builder.append(cb.getText()).append(RAPPER_SEPARATOR);
}
}
并多次调用它:
appendRapperIfChecked(builder, eminem);
appendRapperIfChecked(builder, dre);
appendRapperIfChecked(builder, tupac);
appendRapperIfChecked(builder, royce);
appendRapperIfChecked(builder, logic);
appendRapperIfChecked(builder, big_sean);
final int length = builder.length();
if (length > 0) {
builder.delete(length - RAPPER_SEPARATOR.length() - 1, length - 1);
app.t(result.replace("x" , builder.toString()));
}
关于java - 单独的字符串输入android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66329546/