二十五、自定义CheckBox

因为需要,需要自己定义个CheckBox。

1.定义checkboxtestxml.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.     <CheckBox   
  7.         android:id="@+id/checkboxxml_CB1"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:background="@drawable/mcheckbox"  
  11.         android:button="@null"  
  12.           
  13.         />  
  14.       
  15.   
  16. </LinearLayout>  


2.定义里面的mcheckbox.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.     <item android:state_checked="true" android:drawable="@drawable/checkbox_select"></item>  
  4.     <item android:state_selected="true" android:drawable="@drawable/checkbox_select"></item>  
  5.     <item android:state_checked="false" android:drawable="@drawable/checkbox"></item>  
  6.   
  7. </selector>  


3.java代码:

  1. import com.login.login.R;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.os.Bundle;  
  6. import android.widget.CheckBox;  
  7. import android.widget.CompoundButton;  
  8. import android.widget.CompoundButton.OnCheckedChangeListener;  
  9. import android.widget.Toast;  
  10.   
  11. public class CheckboxTestActivity extends Activity {  
  12.     private CheckBox checkboxxml_CB1;  
  13.     private Context context = CheckboxTestActivity.this;  
  14.   
  15.     @Override  
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         // TODO Auto-generated method stub  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.checkboxtestxml);  
  20.           
  21.         init();  
  22.     }  
  23.   
  24.     private void init() {  
  25.         checkboxxml_CB1 = (CheckBox) findViewById(R.id.checkboxxml_CB1);  
  26.           
  27.         checkboxxml_CB1.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
  28.               
  29.             @Override  
  30.             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {  
  31.                 if(isChecked){  
  32.                     Toast.makeText(context, "选择了"2).show();  
  33.                 }else{  
  34.                     Toast.makeText(context, "没选择"2).show();  
  35.                       
  36.                 }  
  37.             }  
  38.         });  
  39.     }  
  40.   
  41. }  


图片资源直接在百度上面找吧,就2个,一个是选中状态的,一个是没选中的。

 

注意点:

1.另外必须将android:button设置为@null

原文地址:https://www.cnblogs.com/liyuzhao/p/3785648.html