disable checkboxes after certain number of checkboxes are checked - java

I have 6 checkboxes and I would want for example if I have a variable a=2 to let the user check 2 checkboxes and make the other disabled..if I have a=3 to let the user check 3 checkboxes and disable the rest and so on..This is what I tried:
public void itemClicked(View v) {
//code to check if this checkbox is checked!
CheckBox checkBox = (CheckBox)v;
check1=(CheckBox)findViewById(R.id.check1);
check2=(CheckBox)findViewById(R.id.check2);
check3=(CheckBox)findViewById(R.id.check3);
check4=(CheckBox)findViewById(R.id.check4);
check5=(CheckBox)findViewById(R.id.check5);
check6=(CheckBox)findViewById(R.id.check6);
if(a==1)
{
only one can be checked the others get disabled
}
}
}
and a part of the xml file is:
<CheckBox android:id="#+id/check1"
android:layout_width="140dp"
android:layout_height="250dp"
android:scaleX="1.0"
android:scaleY="1.0"
android:button="#layout/cb_selector"
android:layout_marginLeft="80dp"
android:layout_marginTop="505dp"
android:onClick="itemClicked"
/>
<CheckBox android:id="#+id/check2"
android:layout_width="140dp"
android:layout_height="250dp"
android:scaleX="1.0"
android:scaleY="1.0"
android:button="#layout/cb_selector"
android:layout_marginLeft="365dp"
android:layout_marginTop="505dp"
/>
How can I achive this?

You need an array of checkboxes and a your check of variable in onCheckedChange.
CheckBox[] cba;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cba = new CheckBox[]{
(CheckBox)findViewById(R.id.check1),
(CheckBox)findViewById(R.id.check2),
(CheckBox)findViewById(R.id.check3),
(CheckBox)findViewById(R.id.check4),
(CheckBox)findViewById(R.id.check5),
(CheckBox)findViewById(R.id.check6)
};
//here set onChechedChange for all your checkboxes
for (CheckBox cb:cba) {
cb.setOnCheckedChangeListener(cbListener);
}
}
CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkEnoughAndMakeDisabled(cba);
}
};
private void checkEnoughAndMakeDisabled(CheckBox checkBoxes[]){
int countChecked =0;
for (CheckBox cb:checkBoxes){
cb.setEnabled(true);
if (cb.isChecked()) countChecked++;
}
//your variable
if (a <= countChecked) {
for (CheckBox cb:checkBoxes){
if (!cb.isChecked())cb.setEnabled(false);
}
}
}
Ps: Also i think the best practice for such issues is usage of Data-Binding, but it is other story

If there's a case where the user can select only one option, you better use radio buttons.
Anyway, here's a good and simple answer: https://stackoverflow.com/a/20041237/5280641.

Related

I need to enable or disable the POSITIVE button of an AlertDialog based on input fields and dismiss only on good validation

I would like to enable or disable the OK (POSITIVE) button of the AlertDialog with a custom layout such that I can:
Disable the OK button initially
Enable the OK button when all required fields have been entered
Disable the OK button again if a required field has been cleared
Perform validation after the OK button is selected and prevent dismissal upon validation errors
Assume the AlertDialog layout is as follows with one required field description and one optional field age:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<EditText
android:id="#+id/description"
android:hint="Field is required"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="#id/age" />
<EditText
android:id="#+id/age"
android:hint="Optional"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#id/description"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Assume I have a button to kick off the dialog
Button b = findViewById(R.id.main_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG,"button");
View viewcustom = getLayoutInflater().inflate(R.layout.customdialog,null);
EditText edt1 = viewcustom.findViewById(R.id.description);
EditText edt2 = viewcustom.findViewById(R.id.age);
// render alertdialog
}
});
Here is the code. I created a custom layout with 2 EditText fields and require only 1 to be entered. The first is treated as just text that must be present and the second is treated as an optional Age. The final example shows how to add validation and to "not dismiss" after OK is pressed and validation fails.
The OK button is initially disabled and when data is entered in the first text field the OK button is enabled.
By controlling the enable/disable of the positive (OK) button it requires the user to the enter fields necessary (rather than giving them an error when omitted).
Note that when the user clears the same field the OK button is disabled.
You can also add a hint to the EditText field(s) to indicate required (shown in second example).
Note that this was used as reference for the EditText listening (as I linked to in comment).
Finally, the last demo shows if you really wanted to show an error on field validation after the OK button is enabled and pressed. (From here.)
This should be obvious how to expand it to all your EditText fields. And bear in mind you can an condition to enabling the OK button - here it is just at least one character.
Button b = findViewById(R.id.main_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG,"button");
View viewcustom = getLayoutInflater().inflate(R.layout.customdialog,null);
EditText edt1 = viewcustom.findViewById(R.id.description);
EditText edt2 = viewcustom.findViewById(R.id.age);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this)
.setView(viewcustom)
.setPositiveButton("Ok", (dialogInterface, i) -> {
String d = edt1.getText().toString();
String a = edt2.getText().toString();
Toast.makeText(MainActivity.this,d, Toast.LENGTH_LONG).show();
});
alertDialog.setNegativeButton("Cancel", null);
AlertDialog ad = alertDialog.create();
edt1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence sequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence sequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
if (edt1.getText().length() > 0) {
// if user enters anything then enable - modify criteria as desired
ad.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(true);
} else {
// if user deletes entry then back to disabled
ad.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
}
});
// Initially OK button is disabled.
ad.show();
ad.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
});
And demo:
You can also add a hint to each field to indicate it is required if nothing is entered as in :
<EditText
android:id="#+id/description"
android:hint="Field is required"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="#id/age" />
Finally, if you really, really want to allow the OK but then do further validation to display errors then add the following. Note that the second field is treated as an Age field and the data entered must be an integer. A bit contrived but used to show an example.
// add this after the AlertDialog create()
ad.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface anInterface) {
Button b = ad.getButton(DialogInterface.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do some validation on edit text
String s = edt2.getText().toString();
try {
Integer age = Integer.valueOf(s);
Toast.makeText(MainActivity.this,d+":"+age, Toast.LENGTH_LONG).show();
ad.dismiss();
} catch (Exception e) {
// complain
Toast.makeText(MainActivity.this, "Age must be an integer", Toast.LENGTH_LONG).show();
}
}
});
}
});
And demo of requiring the optional Age to be an integer:

Have a disabled onClick?

I want to be able to respond to a click event on a disabled switch, is that possible?
I have a switch that is not enabled until the user fills in some information, so it looks like this:
I want to prompt the user to fill out the information if they click on the disabled switch with a dialog, like so:
mySwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!userInfo.isFilled){
new AlertDialog.Builder(MainActivity.this)
.setTitle("Fill out info first!")
.setMessage("You must first fill out info before turning on this featurel")
.setNeutralButton("Okay", null)
.show();
}
}
});
However, the onClick() is not triggered when I click on the disabled switch, so how do I get when the user clicks on it?
You could place a transparent View on top of the Switch and toggle its enabled state opposite the Switch, and show the message when this overlaid View is clicked.
From the View.java source code,
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don't have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn't want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
the enabled flag ensures the UnhandledEvents are consumed however not passed along to the listeners,thereby bypassing all your possible code.So it is not possible to listen to events on a disabled view.
That said, your options are,
Change the style to mimic that of a disabled view as mentioned here,and then add your required functionality.
Add a overlay invisible view to perform your required functionality which you can set to Gone once the view should be enabled.
Use something apart from enabled,(you could setClickable(false) and consume touch events)
You can set onTouchListener and react to boolean (e.g isToggleEnable) reference with respect to the user's previous actions:
mySwitch.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(!isToggleEnable){
//Taost here
}
//If isToggleEnable = false on return OnClickListener won't be called
return isToggleEnable;
}
});
When it is disabled, setEnabled(false), these listeners won't work.
Try this way: don't disable it, use the setOnCheckedChangeListener and check against your is-entry-filled in there:
use setOnCheckedChangeListener
switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isEntryFilled) {
buttonView.setChecked(false);
// your alert dialog
} else {
}
}
});
this will re-check it back to off and pop your alert, until isEntryFilled is met.
EDIT
OR instead of setEnabled(false), use setClickable(false) or android:clickable="false" since docs say setClickable() is tied to click-events.
and instead of OnClickListener, try OnTouchListener. It will register your on-down-touch (and ignore your on-up-touch), since a click consists of down+up.
switch.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!isEntryFilled) {
buttonView.setChecked(false);
// your alert dialog
}
return false;
}
});
then somewhere else, where you check for isEntryFilled, reactivate your switch with switch.setClickable(true)
Try setting setFocusable(false) and setEnabled(true) on your switch. That way, click events will be fired while the switch still being "disabled". Taken from this answer.
mySwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isClick()){
//Your Valid Code
}else{
//Make our switch to false
new AlertDialog.Builder(MainActivity.this)
.setTitle("Fill out info first!")
.setMessage("You must first fill out info before turning on this featurel")
.setNeutralButton("Okay", null)
.show();
}
}
});
public Boolean isClick(){
//check condition that user fill details or not
//if yes then return true
// else return false
}
Let the Parent View intercept ClickEvents or TouchEvents, when its detected check if the receiving View is disabled, and do what you have to do.
Edit
"it doesn't work when disabled?"
try these codes, Im use LinearLayout for easy aligment. but overall it should give you an example
this is a full example
XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="70dp"
android:background="#273746">
<FrameLayout
android:layout_width="match_parent"
android:id="#+id/ass"
android:background="#drawable/abc_popup_background_mtrl_mult"
android:layout_height="match_parent">
</FrameLayout>
MainActivity onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry_screen);
FrameLayout fl = (FrameLayout)findViewById(R.id.ass);
Test t = new Test(this);
FrameLayout.LayoutParams lp = (LayoutParams) fl.getLayoutParams();
lp.height = LayoutParams.MATCH_PARENT;
lp.width = LayoutParams.MATCH_PARENT;
t.setOrientation(LinearLayout.VERTICAL);
t.setLayoutParams(lp);
fl.addView(t);
t.setBackgroundColor(Color.YELLOW);
Button b = new Button(this);
b.setText("patricia");
t.addView(b);
b = new Button(this);
b.setText("monica");
t.addView(b);
b = new Button(this);
b.setText("rebecca");
t.addView(b);
}
Test.java
public class Test extends LinearLayout {
public Test(Context context) {
super(context);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
StringBuilder sb = new StringBuilder();
sb.append("intercept \n\r");
int x = (int)event.getX(),
y= (int)event.getY();
for(int i =0; i< getChildCount(); i++){
int[] pos = new int[]{getChildAt(i).getLeft(),getChildAt(i).getTop(),
getChildAt(i).getMeasuredWidth(),
getChildAt(i).getMeasuredHeight()};
sb.append(getChildAt(i).getLeft()+", ");
sb.append(getChildAt(i).getTop()+", ");
sb.append(getChildAt(i).getMeasuredWidth()+", ");
sb.append(getChildAt(i).getMeasuredHeight());
sb.append("\n\r");
sb.append(isInBounds(pos, x, y));
sb.append("\n\r");
}
sb.append("x is ");
sb.append(x);
sb.append("y is ");
sb.append(y);
Toast.makeText(getContext(),sb.toString() , Toast.LENGTH_LONG).show();
return super.onInterceptTouchEvent(event);
}
private boolean isInBounds(int[] dimen, int x, int y){
return ((x >= dimen[0] && x < (dimen[0] + dimen[2]))
&& (y >= dimen[1] && y < (dimen[1] + dimen[3])));
}
}
Now The one you click will check out to be true, that is the child, now when it checks out to be true you can do something like this
View v = getchildAt(pos);
//its the one that is tapped or clicked
if(!v.isEnabled()){
//this is the guy you want now, do what you want to do
for click event i am not try this, but you could just do View.performClick() or put your Dialog in the ViewGroup class and call it
actually you could use the View..getClipBounds() to save yourself from int array
Set the disable switches on click listener to change the listeners of the other switches. For example:
Switch s = (Switch) findViewById(R.id.SwitchID);
if (s != null) {
s.setOnCheckedChangeListener(this);
}
/* ... */
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(this, "The Switch is " + (isChecked ? "on" : "off"),
Toast.LENGTH_SHORT).show();
if(isChecked) {
//do stuff when Switch is ON
//this is where you set your normal state OnClickListner
} else {
mySwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!userInfo.isFilled){
new AlertDialog.Builder(MainActivity.this)
.setTitle("Fill out info first!")
.setMessage("You must first fill out info before turning on this featurel")
.setNeutralButton("Okay", null)
.show();
}
}
});
}
}
I'm guessing you've disabled the switch using switch.setEnabled(false). If so, the onclick event will not trigger. If you still want to handle a click action when the switch is disabled, you can use .setOnTouchListener()...
You're best bet however would be to use .setOnCheckedChangeListener() and keeping the switch enabled. Basically when onCheckChanged() gets called, you can popup your dialog if the switch value is on and when the user click ok, you default the switch back to off.
mSwitched.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked && !userInfo.isFilled){
new AlertDialog.Builder(Activity.this)
.setTitle("Fill out info first!")
.setMessage("You must first fill out info before turning on this featurel")
.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mSwitched.setChecked(false);
}
})
.show();
}
}
});
You can do this in a different way,Give a root layout to toggle button with same width and height of toggle button
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!--Root layout to toggle button with same height and width
of toggle button-->
<LinearLayout
android:layout_width="wrap_content"
android:id="#+id/linear"
android:layout_height="wrap_content">
<ToggleButton
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
/>
</LinearLayout>
</RelativeLayout>
When you disable the button,make the button as not focasable and clickable .Then os will handover touch functionality to rootlayout.In the root layout click listner we can write the click logic when the button is not enabled
public class MainActivity extends AppCompatActivity {
ToggleButton button;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (ToggleButton) findViewById(R.id.button);
linearLayout= (LinearLayout) findViewById(R.id.linear);
//disabling button
button.setEnabled(false);
button.setClickable(false);
button.setFocusableInTouchMode(false);
button.setFocusable(false);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//write the logic here which will execute when button is enabled
}
});
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//write the logic here which will execute when button is disabled
}
});
}
}
When you enable the button,make button to clickable and focausable.
//enabling button
button.setEnabled(true);
button.setClickable(true);
button.setFocusableInTouchMode(true);
button.setFocusable(true);

CheckBox doesnt reponse to check state (Android Studio)

Lets suppose I have 2 checkbox ("checkbox1" and "checkbox2") and I set: SetChecked(true) For "checkbox1" and : SetChcked(false) for "checkbox2". my purpose is to relate them and switch between the check state when I click on one of them ,(if "checkbox1" is checked and I checked "checkbox2" then "checkbox2" will be checked and "checkbox1" will be unchecked and by viceversa)
Here is my code :
final CheckBox ChckBoxNo = (CheckBox) promptsView.findViewById(R.id.ChkBoxNo);
final CheckBox ChckBoxYes = (CheckBox) promptsView.findViewById(R.id.ChkBoxYes);
ChckBoxNo.setChecked(true);
ChckBoxYes.setChecked(false);
ChckBoxNo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (ChckBoxNo.isChecked()) {
ChckBoxYes.setChecked(false);
} else if (!ChckBoxNo.isChecked()) {
ChckBoxYes.setChecked(true);
}
}
});
ChckBoxYes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (ChckBoxYes.isChecked()) {
ChckBoxNo.setChecked(false);
} else if (!ChckBoxYes.isChecked()) {
ChckBoxNo.setChecked(true);
}
}
});
//these if's allways response to "ChckBoxNo.IsChecked()" ,even if its the
// opposite and "ChckBoxYes.isChcked()"
if(ChckBoxYes.isChecked())
{do ...
}
else if (ChckBoxNo.isChecked()
{ do ...
}
When I run the app by visibility evreything is good When I click on "ChckBoxYes" it's checked and "ChckboxNo" is unchecked and viceversa,but its allways get the default value that I set before implenting the "OnCheckedChangeListener" (ChckBoxNo.SetChcked(true), ChckBoxYes.SetChecked(false) , even if its opposite and "ChckBoxYes" is chcked)
What should I do in order to fix that?
thanks !
This is not the right way to approach your problem. Luckily there is already a built-in component for that called RadioGroup. You could do something like this:
Have your Activity's xml file something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/radio_button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CheckBox1" />
<RadioButton
android:id="#+id/radio_button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CheckBox2" />
</RadioGroup>
</LinearLayout>
And in your Activity you can interact with this component and handle whatever you want when any of the RadioButtons are tapped like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.radio_button1) {
//First is checked
} else if (checkedId == R.id.radio_button2) {
// Second is checked
}
}
});
}
}

How to create custom Android radio buttons?

I've got a couple radio button options in my android app, but I want them to look totally different. More something like below (quick mockup) in which you simply click the words you want and it makes them bold and underlined.
Does anybody know how I can achieve something like this? All tips are welcome!
Generally speaking, to override the look of default widgets, you'll need to create a drawable folder and put all of your xml definitions in that folder. Then reference that xml file within the RadioButton block of your layout.
Here's a good blog post on how to do all that:
http://blog.devminded.com/posts/custom-android-radiobutton
I know it might be late, but it is not a reason to keep the solution for myself.
1) You need to implement the .XML layout for the RadioGroup and it's RadioButtons. Set the RadioGroup children orientation with Horizontal value to display the button side by side. Setting the RadioButton button with #null value to hide the default selector
As following:
<RadioGroup
android:id="#+id/my_radiogroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/i_like_radiobutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="#null"
android:padding="10dp"
android:text="I Like"
android:textColor="#android:color/holo_orange_light" />
<RadioButton
android:id="#+id/i_dont_like_radiobutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="#null"
android:padding="10dp"
android:text="I Dont Like"
android:textColor="#android:color/holo_orange_light" />
</RadioGroup>
2) In your Activity class, initialize them and set their listener. The listener should keep track of the changes of the RadioButton changes and set the UI changes according to the state either select or unselect. As following:
RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.my_radiogroup);
RadioButton likeRadioButton = (RadioButton) findViewById(R.id.i_like_radiobutton);
RadioButton dontLikeRadioButton = (RadioButton) findViewById(R.id.i_dont_like_radiobutton);
//Like button listener
likeRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//Make the text underlined
SpannableString content = new SpannableString(getString(R.string.like_text));
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
buttonView.setText(content);
//Make the text BOLD
buttonView.setTypeface(null, Typeface.BOLD);
} else {
//Change the color here and make the Text bold
SpannableString content = new SpannableString(getString(R.string.like_text));
content.setSpan(null, 0, content.length(), 0);
buttonView.setText(content);
buttonView.setTypeface(null, Typeface.NORMAL);
}
}
});
//Don't Like button listener
dontLikeRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//Change the color here and make the Text bold
SpannableString content = new SpannableString(getString(R.string.like_text));
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
buttonView.setText(content);
buttonView.setTypeface(null, Typeface.BOLD);
} else {
//Change the color here and make the Text bold
SpannableString content = new SpannableString(getString(R.string.like_text));
content.setSpan(null, 0, content.length(), 0);
buttonView.setText(content);
buttonView.setTypeface(null, Typeface.NORMAL);
}
}
});
3) Now, the RadioButton will change it's color and it's TextStyle according to it's state automatically. You can add more customization if you want.
4) For performing the required action when the user select any of the Buttons, we need to override the setOnCheckedChangeListener method for the RadioGroup as following:
genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.i_dont_like_radiobutton) {
//Do some actions
} else if (checkedId == R.id.i_like_radiobutton){
}
}
});
The final output will be very similar the the question image except the separator.
I hope it helps.

Automatic Checkbox list with 5 sec. delay in android

I want to show automatic checklist in android. For example I can have 4 list of item with unchecked check box adjutant to that.
After 5 sec. delay I want to check the first item then move on to second. At the end of 20 sec. I should have all 4 check box checked one by one.
Any idea how should I go on doing this ? I can use list view with checkbox opeion on ..right ??
I am a .net programmer and this is new experience for me so any comment / advise is appreciated.
Here is a basic example I've just written:
public class AutoChecker extends Activity {
private CheckBox checkbox1;
private CheckBox checkbox2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkbox1 = (CheckBox) findViewById(R.id.checkbox_1);
checkbox2 = (CheckBox) findViewById(R.id.checkbox_2);
new CheckerAsync(AutoChecker.this).execute(checkbox1, checkbox2);
}
private class CheckerAsync extends AsyncTask<CheckBox, CheckBox, Void>{
private Activity mActivity;
private CheckerAsync(Activity activity) {
mActivity = activity;
}
#Override
protected Void doInBackground(final CheckBox... checkboxes) {
try {
for(int i = 0, j = checkboxes.length; i < j; i++ ){
Thread.sleep(5000);
publishProgress(checkboxes[i]);
}
} catch (InterruptedException e) {}
return null;
}
#Override
public void onProgressUpdate(final CheckBox... checkboxes){
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
checkboxes[0].setChecked(true);
}
});
}
}
}
This is the XML layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<CheckBox
android:id="#+id/checkbox_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Checkbox 1"
/>
<CheckBox
android:id="#+id/checkbox_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Checkbox 2"
/>
</LinearLayout>
Explanation
It uses a class that extends AsyncTask which allows you to use threading in a easy to use/understand way. The way this class is executed is kind of simple:
new CheckerAsync(AutoChecker.this).execute(checkbox1, checkbox2);
You can add as many checkboxes as you want. For instance:
new CheckerAsync(AutoChecker.this).execute(checkbox1, checkbox2, checkbox4, checkbox3);
By the way, I don't know why you are trying to do this. But, if it's for testing purposes, you better take a look at the instrumentation framework.
For the automatic checking with delay, you should use an AsyncTask, like a thread where you can modify things within the Android main UI thread, i.e. like checking the checkboxes.
http://developer.android.com/resources/articles/painless-threading.html
http://www.xoriant.com/blog/mobile-application-development/android-async-task.html
http://developer.android.com/reference/android/os/AsyncTask.html
The checkboxes can be part of a listview, but don't have to be. You can also add them into a LinearLayout with vertical orientation one by one.

Categories

Resources