我有16个复选框,我动态尝试获取一次检查,我已经从我的布局中的checkBox1-checkbox16编号。
我使用的代码如下
package com.example.test;
import android.R.string;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Compare1 extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.commac1);
// setdesign();
checkbox();
}
private void checkbox() {
// TODO Auto-generated method stub
for(int a=1;a<17;a++){
String cb="checkBox"+a;
int id=getResources().getIdentifier(cb, "id", getPackageName());
CheckBox cb1=(CheckBox) findViewById(id);
if(cb1.isChecked()){
Toast.makeText(this, "you selected" +cb, Toast.LENGTH_SHORT).show();
}}}}
这似乎没有用。可以有人帮我这个。感谢
答案 0 :(得分:1)
将此添加到您的班级(基于@ FMontano的建议)
public class Compare1 extends Activity implements CompoundButton.OnCheckedChangeListener {
...
然后尝试这个方法1:
CheckBox cb1 = findViewById(id);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Toast.makeText ...
}
});
或者这个方法2:
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.checkbox1:
//your toast
break;
case R.id.checkbox2:
//your toast
break;
case R.id.checkbox3:
//your toast
break;
}
}
并将其命名为像这样使用
CheckBox cb1 = findViewById(R.id.checkbox1);
cb1.setOnCheckedChangeListener(this);
答案 1 :(得分:0)
使用IsabelHM建议,你最终会得到一些看起来像这样的东西:
package com.example.test;
import android.R.string;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Compare1 extends Activity implements CompoundButton.OnCheckedChangeListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.commac1);
// setdesign();
checkbox();
}
private void checkbox() {
// TODO Auto-generated method stub
for(int a=1;a<17;a++){
String cb="checkBox"+a;
int id=getResources().getIdentifier(cb, "id", getPackageName());
CheckBox cb1=(CheckBox) findViewById(id);
cb1.setOnCheckedChangeListener(this);
}
}
/// Will be called by all the checkboxes
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.checkbox1:
//your toast
break;
case R.id.checkbox2:
//your toast
break;
case R.id.checkbox3:
//your toast
break;
...
case R.id.checkbox16:
//your toast
break;
}
}
}