我是Android新手,请帮助我。
如果启用了以下代码中的两个复选框,我怎样才能实现打印值?
public EditText output;
Button one;
int a;
CheckBox check,check1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output =(EditText)findViewById(R.id.editText1);
one=(Button)findViewById(R.id.button1);
check = (CheckBox)this.findViewById(R.id.checkbox1);
check1 = (CheckBox)this.findViewById(R.id.checkbox2);
check.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
a=100;
}
else{
a=0;
}
}
});
check1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
a=100;
}
else{
a=0;
}
}
});
//this statment is wrong. if((check.isChecked() == true)&&(check.isChecked() == true)){
a=200;
}
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(v==one){
output.setText(""+a);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
答案 0 :(得分:1)
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkbox_meat:
if (checked)
// Put some meat on the sandwich
else
// Remove the meat
break;
case R.id.checkbox_cheese:
if (checked)
// Cheese me
else
// I'm lactose intolerant
break;
// TODO: Veggie sandwich
}
}
答案 1 :(得分:1)
在按钮的onClick方法
if((checkBox1.isChecked()) && (checkBox2.isChecked)){
editText.setText("Both are checked");
}
我们不需要分配任何变量,因为isChecked方法返回一个布尔值,因此可以直接在里面检查if。
答案 2 :(得分:0)
将两个复选框声明为final,并与
进行比较if (check.isChecked() == true && check1.isChecked == true)
就我而言,它有效。示例:检查按钮的OnClick方法中的复选框的状态
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CheckBox check = (CheckBox)findViewById(R.id.check);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("Tag-test", "Value:" + check.isChecked());
}
});
}
答案 3 :(得分:0)
This is my new code
public EditText output;
Button one;
int a;
CheckBox check,check1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output =(EditText)findViewById(R.id.editText1);
one=(Button)findViewById(R.id.button1);
check = (CheckBox)this.findViewById(R.id.checkbox1);
check1 = (CheckBox)this.findViewById(R.id.checkbox2);
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
if(check.isChecked()){a=100;}
else{a=0;}
if(check1.isChecked()){a=100;}
else{a=0;}
if(check.isChecked()&& check1.isChecked())
{
a=200;
}
else{a=0;}
if(v==one)
{
output.setText(""+a);
}
}});