Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.designingknights.unboundradiogroup;
- import android.app.Activity;
- import android.support.annotation.NonNull;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.RadioButton;
- /**
- * Created by Timothy Winters on 5/23/2018.
- */
- public class UnboundRadioGroup implements RadioButton.OnClickListener
- {
- private ViewGroup viewGroup;
- private String groupTag;
- private int lastChecked = -1;
- private Activity activity;
- private OnClickListener clickListener;
- /**
- * Instantiates a new Custom radio group.
- *
- * @param activity the activity
- * @param viewGroupID the view group id
- */
- public UnboundRadioGroup(@NonNull Activity activity, int viewGroupID)
- {
- this.activity = activity;
- this.viewGroup = (ViewGroup) activity.findViewById(viewGroupID);
- init();
- }
- /**
- * Instantiates a new Custom radio group.
- *
- * @param activity the activity
- * @param viewGroup the view group
- */
- public UnboundRadioGroup(@NonNull Activity activity, ViewGroup viewGroup)
- {
- this.activity = activity;
- this.viewGroup = viewGroup;
- init();
- }
- private void init()
- {
- clickListener = null;
- // buildGroup(viewGroup);
- }
- /**
- * Create group by tag.
- *
- * @param groupTag the group tag
- */
- public void createGroupByTag(String groupTag)
- {
- this.groupTag = groupTag;
- buildGroup(viewGroup);
- }
- private void buildGroup(@NonNull ViewGroup viewGroup)
- {
- int count = viewGroup.getChildCount();
- for (int i = 0; i < count; i++)
- {
- View view = viewGroup.getChildAt(i);
- if (view instanceof ViewGroup)
- {
- buildGroup((ViewGroup) view);
- }
- else if (view instanceof RadioButton)
- {
- RadioButton radioButton = (RadioButton) view;
- if (radioButton.getTag().equals(groupTag))
- {
- radioButton.setOnClickListener(this);
- }
- }
- }
- }
- /**
- * Add.
- *
- * @param radioButton the radio button
- */
- public void add(@NonNull RadioButton radioButton)
- {
- radioButton.setOnClickListener(this);
- }
- @Override
- public void onClick(View v)
- {
- int checked = v.getId();
- if (checked != lastChecked)
- {
- ((RadioButton) v).setChecked(true);
- if (clickListener != null) clickListener.OnClick((RadioButton) v);
- if (lastChecked != -1)
- {
- ((RadioButton) activity.findViewById(lastChecked)).setChecked(false);
- }
- lastChecked = checked;
- }
- }
- /**
- * Sets on click listener.
- *
- * @param clickListener the click listener
- */
- public void setOnClickListener(OnClickListener clickListener)
- {
- this.clickListener = clickListener;
- }
- /**
- * The interface On click listener.
- */
- public interface OnClickListener
- {
- /**
- * On click.
- *
- * @param radioButton the radio button
- */
- public void OnClick(RadioButton radioButton);
- }
- }
Add Comment
Please, Sign In to add comment