Use of RadioButton widget in android studio

 

RadioButton provide option for selecting different function. for eg. there are multiple functions like add, subtract, divide, multiply, etc  We can select one of them which we want to apply.

In above pic I selected sub button and and got result.

Here is Program for this.

public class MainActivity extends AppCompatActivity {
    EditText e1, e2, e3;
    RadioButton radd,rsub,rprod,rdiv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        e1=(EditText)findViewById(R.id.e1);
        e2=(EditText)findViewById(R.id.e2);
        e3=(EditText)findViewById(R.id.e3);
        radd=(RadioButton) findViewById(R.id.radd);
        rsub=(RadioButton) findViewById(R.id.rsub);
        rprod=(RadioButton) findViewById(R.id.rprod);
        rdiv=(RadioButton) findViewById(R.id.rdiv);
    }
public void perform(View view)
{
    try
    {
        int a=Integer.parseInt("" + e1.getText());
        int b=Integer.parseInt("" + e2.getText());
        int result=0;
        if(radd.isChecked())
        {
            result=a+b;
        }
        if(rsub.isChecked())
        {
            result=a-b;
        }
        if(rprod.isChecked())
        {
            result=a*b;
        }
        if(rdiv.isChecked())
        {
            result=a/b;
        }

        e3.setText("" + result);

    }
    catch (Exception ex)
    {
        System.out.println(ex);
        e3.setText(ex.getMessage());
    }
}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 

Leave a Reply