我在android中制作了一个简单的checkbo [x演示程序,因为我已经放了一个chekbox和一个按钮。我想要的是当按下chekbox并按下按钮时tot toast显示“我接受”其他当按钮按下吐司生成的“我不接受”...我已经成功但问题是当我取消选中chekbox ..它直接显示吐司(没有点击按钮);
mainActivity.java
package com.example.chechboxdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
CheckBox c1;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c1=(CheckBox)findViewById(R.id.checkBox1);
b=(Button)findViewById(R.id.button1);
c1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
if(c1.isChecked()){
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "i accept", 1).show();
}
});
}
else{
Toast.makeText(getApplicationContext(), "i don't accept", 1).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
答案 0 :(得分:1)
除非您希望在用户选中/取消选中复选框时发生某些事情,否则不应使用checkChanged侦听器。由于您希望仅在单击按钮时才执行操作,因此您只需要onClickListener,并且它应该是onCheckChangedListener的外部
试试这样:
public class MainActivity extends Activity {
CheckBox c1;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c1=(CheckBox)findViewById(R.id.checkBox1);
b=(Button)findViewById(R.id.button1);
c1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// You don't need to use onCheckChangeListener.
}
});
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(c1.isChecked()){
Toast.makeText(getApplicationContext(), "i accept", 1).show();
}else{
Toast.makeText(getApplicationContext(), "i don't accept", 1).show();
}
}
});
}//end onCreate
}//end MainActivity
答案 1 :(得分:0)
在按钮内移动c1.isChecked()
单击以检查是否选中了CheckBox按钮单击然后根据CheckBox状态显示toast消息。将您的代码更改为:
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(c1.isChecked()){ //<<< check here if checkbox clicked or not
Toast.makeText(getApplicationContext(),
"i accept", 1).show();
}else{
Toast.makeText(getApplicationContext(),
"i don't accept", 1).show();
}
}
});