Create RadioButton RadioGroup dynamically – Android sample

public class MainActivity extends Activity implements OnClickListener {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            RadioGroup radioGroup = new RadioGroup(this);
 
            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            layout.addView(radioGroup, p);
 
            RadioButton radioButtonView = new RadioButton(this);
            radioButtonView.setText("RadioButton");
            radioButtonView.setOnClickListener(this);
            radioGroup.addView(radioButtonView, p);
 
            RadioButton radioButtonView2 = new RadioButton(this);
            radioButtonView2.setText("RadioButton2");
            radioButtonView2.setOnClickListener(mThisButtonListener);
            radioGroup.addView(radioButtonView2, p);
 
    }
 
    public void onClick(View view) {
    	 try {
    	  String s = ((RadioButton) view).getText().toString();
    	  Toast.makeText(MainActivity.this, "This is: " + s,
    			  Toast.LENGTH_LONG).show();
    	 }
    	 catch (Exception e1) {
    	   e1.printStackTrace();
    	 }
    	}
 
    private OnClickListener mThisButtonListener = new OnClickListener() {
        public void onClick(View v) {
        	String s = ((RadioButton) v).getText().toString();
        	Toast.makeText(MainActivity.this, "Hello from 2!" + s,
        			Toast.LENGTH_LONG).show();
        }
    };
 
}
This entry was posted in Android Examples Code and tagged , , , , . Bookmark the permalink.


Comments are closed.

25,737 views