Friday, November 23, 2012

Use of radiogroup and checkbox in an single activity

How to make use of radiogroup.setonCheckedchangelistener and checkbox.setonCheckedchangelistener in a single activity?

http://www.varemads.com/category/android/

This question asked many times because of setonCheckedchangelistener  confusion.
how to find which component is checked either Radiogroup or Checkbox.

Here you need no implement two diffrent CheckedChangeListener for radio group and checkbox.

OnCheckedChangeListener is for radio group and android.widget.CompoundButton.OnCheckedChangeListener is for checkbox.
you need to implement two different CheckedChangeListener refer below code for both radio group and checkbox.

Java file code

public class abcd extends Activity implements OnCheckedChangeListener,android.widget.CompoundButton.OnCheckedChangeListener{

  RadioGroup rd;
  CheckBox cx;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.abcd);

  rd  =  (RadioGroup) findViewById(R.id.radioGroup1);
  cx = (CheckBox) findViewById(R.id.checkBox1);
  
  rd.setOnCheckedChangeListener(this);
  cx.setOnCheckedChangeListener(this);
  

 }
 @Override
 public void onCheckedChanged(RadioGroup group, int checkedId) {

  // Here you can get your Radio button checked id
  System.out.println("radiogroup checked");
  
 }
 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  System.out.println("checkbox checked");
  
 }
 
}

Xml file for this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="RadioButton" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton" />
    </RadioGroup>

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CheckBox" />

</LinearLayout>


http://www.varemads.com/category/android/
Hope this post helpful for you...

No comments:

Post a Comment