将复选框监听器放入按钮监听器

Put check box listener into button listener

我在 Activtiy A.

中保存了 buttoncheckbox

单击保存 button 时,如果 checkbox 选中 ,它将显示 checkbox 文本。

         save.setOnClickListener(new View.OnClickListener() { // if save button clicked

                         @Override
                         public void onClick(View v) {
                                 if(checkbox.isChecked()) {
                                     returnIntent.putExtra("outstation", checkbox.getText().toString());
                                     Toast.makeText(getApplicationContext(),checkbox.getText().toString(),Toast.LENGTH_LONG).show();
                                 }
                              }
                          });

     public void addListenerOnChk() // for checkbox
        {
            checkbox=(CheckBox)findViewById(R.id.checkBox);

            checkbox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        if(((CheckBox)v).isChecked())
                        {
                              // Toast.makeText(getApplicationContext(),checkbox.getText().toString(),Toast.LENGTH_LONG).show();
                        }
                    }

                });
            }

上面的代码工作正常,但看起来很奇怪。我在 OnCreate 方法中定义了 addListenerOnChk() 。如何将复选框放在 save onClick 中而不是创建两个单独的 OnClick ? (一个是保存按钮,另一个是复选框)

第一种方法正确..

第二种方法不需要。 checkBox.isChecked 是您需要使用的一切。您不必也为复选框设置侦听器。

save.setOnClickListener(new View.OnClickListener() { // if save button clicked

  @Override
  public void onClick(View v) {
 if(checkbox.isChecked()) {
returnIntent.putExtra("outstation", checkbox.getText().toString());
Toast.makeText(getApplicationContext(),checkbox.getText().toString(),Toast.LENGTH_LONG).show();
checkbox.setText("your text here");
      } else {
checkbox.setText("");
}
   }
});

希望对您有所帮助

参考这个问题

"How can I put the check box inside save onClick instead of create two seperate OnClick ?"

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //your UI setup and findViewById stuff

        save.setOnClickListener(this);//implement - View.OnClickListener
        checkBox.setOnClickListener(this);//implement - View.OnClickListener
        checkBox.setOnCheckedChangeListener(this);//prefer this one get check box status

    }


    @Override
    public void onClick(View v) {

        if(v.getId()==R.id.save_button){
            //save button action stuff
        } else if(v.getId()==R.id.check_box){
            //checkbox  button action stuff
            Log.i("TAG", " Check box status " + checkBox.isChecked());
        }

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Log.i("TAG", " Check box status " + isChecked);
    }