android开关按钮,Switch,ToggleButton,RadioButton,CheckBox ,多种实现开关按钮

android开关按钮,Switch,ToggleButton,RadioButton,CheckBox ,多种实现开关按钮_第1张图片

方法一:RadioButton



       

                
public class MainActivity extends BaseActivity {

	private RadioGroup main_rg;
	private RadioButton main_rb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		main_rg = (RadioGroup) findViewById(R.id.main_rg_type);
		main_rb = (RadioButton) findViewById(R.id.main_rb_t1);
		main_rg.setOnCheckedChangeListener(new onCheckedChangeListener());
	}

	private int is = 1;

	private class onCheckedChangeListener implements OnCheckedChangeListener {

		public void onCheckedChanged(RadioGroup group, int checkedId) {
			if (main_rb.getId() == checkedId) {
				if (1 == is) {
					is = 0;
					checkedView(main_rb, false);
				} else {
					is = 1;
					checkedView(main_rb, true);
				}
				main_rb.setChecked(false);
			}
		}

		private void checkedView(RadioButton rb, boolean idImg) {
			if (idImg) {
				rb.setButtonDrawable(R.drawable.ic_p);
			} else {
				rb.setButtonDrawable(R.drawable.ic_n);
			}
		}
	}

}

方法二:CheckBox

CheckBox cb = (CheckBox) findViewById(R.id.cb);

		cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) {
							cb.setButtonDrawable(R.drawable.ic_p);
						} else {
							cb.setButtonDrawable(R.drawable.ic_n);
						}
					}
				});
方法三:Switch

Switch sch= (Switch)findViewById(R.id.sch);
sch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked) {
              sch.setBackgroundResource(R.drawable.ic_p);
           }else{
              sch.setBackgroundResource(R.drawable.ic_n);
           }
      }
});

方法四:ToggleButton

ToggleButton tb= (ToggleButton)findViewById(R.id.tb);
tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		tb.setTextOff("");
		tb.setTextOn("");
		if(isChecked) {
			tb.setBackgroundResource(R.drawable.ic_p);
		}else{
			tb.setBackgroundResource(R.drawable.ic_n);
		}
	}
});

****************************************************************************************************************************************************************************************

也可以用配置xml方式写,这里就只写一种,其它都类似...

             style="@style/checkBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
 
  

style="@style/checkBox"

selector自定义样式:check



  
  

代码中设置选中和不选中,就ok...

方法还有很多,这里就不过多介绍了,至于第三方那就多的不计其数... ...

你可能感兴趣的:(android,UI)