Android studio CheckBox(復選框)


實現代碼:

public class MainActivity extends AppCompatActivity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener{ private CheckBox cb_one; private CheckBox cb_two; private CheckBox cb_three; private Button btn_send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cb_one = (CheckBox) findViewById(R.id.cb_one); cb_two = (CheckBox) findViewById(R.id.cb_two); cb_three = (CheckBox) findViewById(R.id.cb_three); btn_send = (Button) findViewById(R.id.btn_send); cb_one.setOnCheckedChangeListener(this); cb_two.setOnCheckedChangeListener(this); cb_three.setOnCheckedChangeListener(this); btn_send.setOnClickListener(this); } @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if(compoundButton.isChecked()) Toast.makeText(this,compoundButton.getText().toString(),Toast.LENGTH_SHORT).show(); } @Override public void onClick(View view) { String choose = ""; if(cb_one.isChecked())choose += cb_one.getText().toString() + ""; if(cb_two.isChecked())choose += cb_two.getText().toString() + ""; if(cb_three.isChecked())choose += cb_three.getText().toString() + ""; Toast.makeText(this,choose,Toast.LENGTH_SHORT).show(); } }

自定義點擊效果

PS:這里素材的原因,有點小...

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="true" android:state_checked="true" android:drawable="@mipmap/ic_checkbox_checked"/> <item android:state_enabled="true" android:state_checked="false" android:drawable="@mipmap/ic_checkbox_normal" /> </selector>

寫好后,我們有兩種方法設置,也可以說一種吧!你看看就知道了~

①android:button屬性設置為上述的selctor

android:button="@drawable/rad_btn_selctor"

②在style中定義一個屬性,然后通過android style屬性設置,先往style添加下述代碼:

    <style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox"> <item name="android:button">@drawable/rad_btn_selctor</item> </style>

然后布局那里:

style="@style/MyCheckBox"

改變文字與選擇框的相對位置

這個實現起來也很簡單 要控制選擇框的位置,兩步即可!設置:

Step 1. android:button="@null"
Step 2. android:drawableTop="@android:drawable/btn_radio"
當然我們可以把drawableXxx替換成自己喜歡的效果!

修改文字與選擇框的距離

有時,我們可能需要調節文字與選擇框之間的距離,讓他們看起來稍微沒那么擠,我們可以:
1.在XML代碼中控制: 使用android:paddingXxx = "xxx" 來控制距離
2.在Java代碼中,稍微好一點,動態計算paddingLeft!

示例代碼如下:

rb.setButtonDrawable(R.drawable.rad_btn_selctor); int rb_paddingLeft = getResources().getDrawable(R.mipmap.ic_checkbox_checked).getIntrinsicWidth()+5; rb.setPadding(rb_paddingLeft, 0, 0, 0);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM