Skip to main content

Create RadioButton RadioGroup Dynamically - Android Tutorial

In this article, we took a look at how to create Radio Buttons Dynamically.

Here I have created this example to create the number of time slots (slot select by Radio Button) in between two selected time.
The final output looks like,



Here I have selected the Start time as 10:00 AM and End time as 12:00 PM and the Time interval between two slots as 15 mins. Therefore the calculation will result as 8 slots.
MainActivity Class
Example shows the Radio group in Grid view - 
Adding the values to an ArrayList,
String slotscounts += " "+slotStartTime+ "-"+slotEndTime +",";
ArrayList<String> slots = new ArrayList<>();
slots.add(slotscounts);
Passing the value to an Adapter class(Base Adapter used)
/*Call adapter to set_radiobuttons_for_timeSlots*/
GridSlotAdapter gridslotadapter = new GridSlotAdapter(MainActivity.this, slots);
/*set an adapter in Gridview*/
slotGrid.setAdapter(gridslotadapter);
Adapter Class
Adapter layout contains a RadioGroup
/* given string will be split by the argument delimiter provided.  */
   String[] temp = slots.split(delimiter);
Create a radio button as final,
final RadioButton[] rb = new RadioButton[temp.length];
Set the dynamic radio button in the radio group
for (int i = 0; i < temp.length; i++) {
rb[i] = new RadioButton(mContext);
holder.radGrp.addView(rb[i]);
rb[i].setText(temp[i]);
}

Complete Coding:
MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    /**Declare Layout Elements**/
    private Button btnStart, btnEnd, btnCreate;
    private EditText edtInterval;
    private GridView slotGrid;
    private static TextView txtTiming, txtLabel;
    private String strStart, strEnd;
    int pHour, pMinute, strInterval, value = 0;
    SimpleDateFormat simpleDateFormat;
    Date inTime, outTime;
    ArrayList<String> slots = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Initializing Layout Elements **/
        btnStart = (Button) findViewById(R.id.idBtnStrTime);
        btnEnd = (Button) findViewById(R.id.idBtnEndTime);
        btnCreate = (Button) findViewById(R.id.idBtnCreate);
        slotGrid = (GridView) findViewById(R.id.idSlotGrid);
        edtInterval = (EditText) findViewById(R.id.idEdtInterval);
        txtTiming = (TextView) findViewById(R.id.idSelectedTime);
        txtLabel = (TextView) findViewById(R.id.idLabel);

        /*recyclerView = (RecyclerView) findViewById(R.id.idRecycleView);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new        GridLayoutManager(getApplicationContext(),2);
        recyclerView.setLayoutManager(layoutManager);*/
        
        /*initialize_onClickListener*/
        btnStart.setOnClickListener(this);
        btnEnd.setOnClickListener(this);
        btnCreate.setOnClickListener(this);

        /*set_button_label*/
        btnCreate.setText("Create Timeslot");
        /*setting_visibility*/
        txtLabel.setVisibility(View.INVISIBLE);
        /*simpleDareFormat_used*/
        simpleDateFormat = new SimpleDateFormat("hh:mm a");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.idBtnStrTime:
                getTime(btnStart);
                break;

            case R.id.idBtnEndTime:
                getTime(btnEnd);
                break;

            case R.id.idBtnCreate:

                if(btnCreate.getText().toString().contentEquals("Create New Timeslot")){
                    btnStart.setText("Select Start Time");
                    btnEnd.setText("Select End Time");
                    btnCreate.setText("Create Timeslot");
                    txtLabel.setVisibility(View.INVISIBLE);
                    slotGrid.setAdapter(null);
                    txtTiming.setText(null);
                    edtInterval.setText(null);

                }else{
                    txtLabel.setVisibility(View.VISIBLE);
                    try {//validation to check all field contains required input
                        value = submit_validation();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    if(value==1){
                        strStart = btnStart.getText().toString().trim();
                        strEnd = btnEnd.getText().toString().trim();
                        strInterval = Integer.parseInt(edtInterval.getText().toString().trim());
                        /*calling_method_to_calculate_numberOfSlots by time difference*/
                        calculateTimeDiff(strStart, strEnd, strInterval);
                    }
                }
                break;

            default:
                break;
        }

    }

    /*method to calculate time difference and number of slots depends upon the given time interval*/
    private void calculateTimeDiff(String strStart, String strEnd, int strInter) {
        String slotscounts="";
        slots.clear();
        try {
            Calendar startCalendar = Calendar.getInstance();
            Calendar endCalendar = Calendar.getInstance();

            startCalendar.setTime(simpleDateFormat.parse(strStart));
            endCalendar.setTime(simpleDateFormat.parse(strEnd));

            while (endCalendar.after(startCalendar)) {
                String slotStartTime = simpleDateFormat.format(startCalendar.getTime());

                startCalendar.add(Calendar.MINUTE, strInter);
                String slotEndTime = simpleDateFormat.format(startCalendar.getTime());

                slotscounts += " "+slotStartTime+ "-"+slotEndTime +",";
            /*    slots.add(slotStartTime + " - " + slotEndTime);*/
                Log.d("DATE", slotStartTime + " - " + slotEndTime +""+slots.size());

            }
            slots.add(slotscounts);

            /*Call adapter to set_radiobuttons_for_timeSlots*/
            GridSlotAdapter gridslotadapter = new GridSlotAdapter(MainActivity.this, slots);
            slotGrid.setNumColumns(2);
            slotGrid.setAdapter(gridslotadapter);

          //recycle_view
           /* gridAdapter = new GridAdapter(MainActivity.this, recyclerView, slots);
            recyclerView.setAdapter(gridAdapter);*/

            btnCreate.setText("Create New Timeslot");

        }catch (ParseException e){
        }

    }
    /*validation_method*/
    private int submit_validation() throws ParseException {
        int i=0;
        strStart = btnStart.getText().toString().trim();
        strEnd = btnEnd.getText().toString().trim();
        String strIntTime = edtInterval.getText().toString().trim();

        if(!validateDateFormat(strStart)){
            Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
                    "Select Start Time", Snackbar.LENGTH_LONG);
            snackbar.show();

        }else if(!validateDateFormat(strEnd)){
            Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
                    "Select End Time", Snackbar.LENGTH_LONG);
            snackbar.show();

        }else if(isTimeAfter(strStart, strEnd)){
            Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
                    "End time should less than Start time", Snackbar.LENGTH_LONG);
            snackbar.show();
        }else if(!(strIntTime!=null && strIntTime.length()>0)){
            edtInterval.setError("Enter time interval for each timeslot");
        } else{
            edtInterval.setError(null);
            i=1;
        }
        return i;
    }
    /*validation_to whether the dates has selected*/
    private boolean validateDateFormat(String strTime) {
        boolean valid = true;
        try {
            inTime = simpleDateFormat.parse(strTime);
        } catch (Exception  e) {
            valid = false;
        }
        return valid;
    }
    /*validation_to check_FROM date should not greater than TO date*/
    private boolean isTimeAfter(String strStart, String strEnd) throws ParseException {
        inTime = simpleDateFormat.parse(strStart);
        outTime = simpleDateFormat.parse(strEnd);

        if (outTime.after(inTime)) { //Same way you can check with after() method also.
            return false;
        } else {
            return true;
        }
    }

    /*TimePicker_function*/
    private void getTime(final Button btnStart) {
        TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this,
                new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay,
                                          int minute) {
                        btnStart.setText(updateTime(hourOfDay,minute));
//                      btnStart.setText(hourOfDay + ":" + minute);//24hrs
                    }
                }, pHour, pMinute, false);
        timePickerDialog.show();
    }
    /*function to convert the 24hrs to 12hrs format*/
    private String updateTime(int hours, int mins) {
        String timeSet = "";
        if (hours > 12) {
            hours -= 12;
            timeSet = "PM";
        } else if (hours == 0) {
            hours += 12;
            timeSet = "AM";
        } else if (hours == 12)
            timeSet = "PM";
        else
            timeSet = "AM";

        String minutes = "";
        if (mins < 10)
            minutes = "0" + mins;
        else
            minutes = String.valueOf(mins);

        // Append in a StringBuilder
        String aTime = new StringBuilder().append(hours).append(':')
                .append(minutes).append(" ").append(timeSet).toString();

        return aTime;
    }

    /*static_method_which call from adapter to set selected radiobutton time in textview*/
    public static void settime(String itemTime){
        txtTiming.setText(itemTime);
    }
}

GridSlotAdapter.java
class GridSlotAdapter extends BaseAdapter{
    Context mContext;
    ArrayList<String> slotCntlist;
    View view;
    ViewHolder holder;
    String[] temp;
    String delimiter = ",";
    String itemTime;

    public GridSlotAdapter(Context context, ArrayList<String> slots ) {
        mContext = context;
        slotCntlist = slots;
    }

    @Override
    public int getCount() {
        return slotCntlist.size();
    }
    @Override
    public Object getItem(int position) {
        return position;
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        view=convertView;

        LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = vi.inflate(R.layout.radiogroup,parent, false);
            holder = new ViewHolder();

            holder.radGrp = (RadioGroup) convertView.findViewById(R.id.radio_group1);
//            holder.radGrp.setOrientation(LinearLayout.VERTICAL);

            String slots = slotCntlist.get(position);

            /* given string will be split by the argument delimiter provided. */
            temp = slots.split(delimiter);

            final RadioButton[] rb = new RadioButton[temp.length];

            for (int i = 0; i < temp.length; i++) {
                rb[i] = new RadioButton(mContext);
                rb[i].setTextAppearance(mContext, android.R.style.TextAppearance_Small);//just_for_TextSize

                holder.radGrp.addView(rb[i]);
                rb[i].setText(temp[i]);
            }

            /*radioGroup_ClickListener*/
            holder.radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    // TODO Auto-generated method stub
                    for (int i = 0; i < group.getChildCount(); i++) {
                        if (group.getChildAt(i).getId() == checkedId) {
                            itemTime = temp[i];
                            break;
                        }
                    }
                    MainActivity.settime(itemTime);//call_static_method_in MainActivity
                }
            });

            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        return convertView;
    }

    private class ViewHolder {
        RadioGroup radGrp;
    }
}

Implement the onClick listener for radio group to get the value of selected radio button, the selected radio button value will be set in the textview as in an image,

You can check the xml file from the source code attached as zip
____________________________________________________________________________
Sourcecode for the DynamicRadioButton.zip 

Happy Coding...

Comments

Popular posts from this blog

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ______________________________________...

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t...

Bluetooth Chat Application - Android Tutorial

In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section ...