0

我如何将以下内容放在一种方法中。因此,我可以有一个侦听器,而不是两个侦听器,它会检查单击了哪个复选框。谢谢

public void onClick(View view) {
    switch (view.getId()) {
    case R.id.safe:
        if (((CheckBox) view).isChecked()) {
            ((CheckBox) view).setButtonDrawable(R.drawable.tick);
        } else {
            ((CheckBox) view).setButtonDrawable(R.drawable.black);
        }
        break;

    }
}

}

4

3 回答 3

2

您可以实施View.OnClickListener,然后您可以拥有一种方法。

public class NameClass extends Activity implements View.OnClickListener {
   public void onClick(View view) {
      switch(view.getId()) {
         case R.id.someWidget:
            // to do
         break;
         case R.id.anotherWidget:
            // to do
         break;
      }
   }
}


注意:还有一个建议,请尝试查看OnCheckedChangeListener.

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
   switch (buttonView.getId()) {
      case R.id.someButton:
         if (isChecked) {
            // some work
         }
         else {
            // some another work
         }
      break;
   }
}
于 2012-06-25T14:05:07.703 回答
0

您可以在侦听器中检查 ID:

private void setListeners() {
    final View muf = findViewById(R.id.muf);
    final View crewArea = findViewById(R.id.crewArea);

    OnclickListener ocl = new OnClickListener() {
        @OVerride
        public void onClick(View view) {
            Checkbox ck = null;
            switch(view.getId()) {
                case R.id.muf: ck = muf; break;
                case R.id.crewArea: ck = crewArea; break;
            }

            if(ck == null)
                return;

            if (ck.isChecked()) {
                ck.setButtonDrawable(R.drawable.tick);
            } else {
                ck.setButtonDrawable(R.drawable.black);
            }
        }
    };

    muf.setOnClickListener(ocl);
    crewArea.setOnClickListener(ocl);
}
于 2012-06-25T14:11:19.693 回答
0

在当前类中实现 setOnClickListener ......

    private void mufListener() {
        muf = (CheckBox) findViewById(R.id.muf);

        muf.setOnClickListener(this);

    }

    private void crewAreaListener() {
        crewArea = (CheckBox) findViewById(R.id.crewArea);
        crewArea.setOnClickListener(this);

    }



public void onClick(View view) {

                switch(view.getID()){

                case R.id.muf:
                case R.id.crewArea:
                if (((CheckBox) view).isChecked()) {
                    ((CheckBox) view).setButtonDrawable(R.drawable.tick);
                } else {
                    ((CheckBox) view).setButtonDrawable(R.drawable.black);
                      }

                break;
             case R.id.tv2:
                    break;

            }
}
于 2012-06-25T14:04:40.127 回答