Getting information from RadioButtons and Checkboxes - android

I have report which consists of 5 questions (there can be only one answer or multiple choice answer). Question are different for each report. So everytime I generate questions and answers as RadioButtons (one answer) or CheckBoxes (multiple choice answer)...But now I really don't know how to save those answers (I'd like to save to it as _question_id, _answer_id).
How can I assign good _answer_id, to _question_id...
Thanks for help in advance

Try something like this:
public void saveAnswers() {
LinearLayout root = (LinearLayout) findViewById(R.id.frame); //or whatever your root control is
loopQuestions(root);
}
private void loopQuestions(ViewGroup parent) {
for(int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
if(child instanceof RadioGroup ) {
//Support for RadioGroups
RadioGroup radio = (RadioGroup)child;
storeAnswer(radio.getId(), radio.getCheckedRadioButtonId());
}
else if(child instanceof CheckBox) {
//Support for checkboxes
CheckBox cb = (CheckBox)child;
int answer = cb.isChecked() ? 1 : 0;
storeAnswer(cb.getId(), answer);
}
else {
//Support for other controls
}
if(child instanceof ViewGroup) {
//Nested Q&A
ViewGroup group = (ViewGroup)child;
loopQuestions(group);
}
}
}
private void storeAnswer(int question, int answer) {
//TODO: Store your answer to disk
}

I suppose you are using RadioGroup for a group of mutually exclusive RadioButtons? Then:
radioGroup.getCheckedRadioButtonId() // gets Id of clicked RadioButton within group
for CheckBox you must check for every button:
checkBox.isChecked()

Related

Android Studio GridLayout toggle all button

I'm using a Gridlayout with the MyView.java class. I got the code from GridLayout.
I implemented another button under the GridLayout. I want to toggle all (GrigLayout-)Buttons with this button. Does anyone have an Idea how I could do this?
Thank you!!!
You have to revise through all child views, and check if they are toggle buttons. Here is an example, when you want to toggle, call toggleButtons(grid);
private void toggleButtons(ViewGroup v) {
View a;
for(int i = 0; i < v.getChildCount(); i++)
{
a = v.getChildAt(i);
if(a instanceof ViewGroup) {
toggleButtons((ViewGroup) a);
}
else if(a instanceof Button){
// Toggle here
}
}
}

clear all child of a view (RadioGroup) [duplicate]

This question already has answers here:
Uncheck all RadioButton in a RadioButtonGroup
(3 answers)
Closed 7 years ago.
I have a drawer menu with a dynamic option inside it and I got to fill it.
I want to clear all the child of a RadioGroup inside adapter but I didn't find anything.
p.s: I fill all RadioGroup with addView and fill it with CheckBox
ps2: The question is not about the check and uncheck. I want to find out how can remove all child of a view (like RadioGroup).
viewHolder.mRadioGroup.setVisibility(View.VISIBLE);
/////clear viewHolder.mRadioGroup child hear, befor add new child to it
for (int i; i<10; i++) {
RadioButton radioButton = new RadioButton(mContext);
radioButton.setText(selectableValue.getValue());
viewHolder.mRadioGroup.addView(radioButton);
}
Try This :
int count = radioGroup.getChildCount();
if(count>0) {
for (int i=count-1;i>=0;i--) {
View o = radioGroup.getChildAt(i);
if (o instanceof RadioButton) {
radioGroup.removeViewAt(i);
}
}
}
This taken from link here for complex nested layout
private static void disable(ViewGroup layout) {
layout.setEnabled(false);
for (int i = 0; i < layout.getChildCount(); i++) {
View child = layout.getChildAt(i);
if (child instanceof ViewGroup) {
disable((ViewGroup) child);
} else {
child.setEnabled(false);
}
}
}

Select all buttons in my form one by one using for loop-- eclipse for android [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have five buttons in my form with names buttonDo,buttonStop,buttonPause,buttonPlay,buttonselect. How to I select all the buttons on by one in for loop to check some condition. I need to a code where it finds total no of buttons on its own and keeps incrementing on its own till it finds the last button.
Plz help me out.
Try with that code, the first function start iterate, the second ( called from the first ) walk through the View three and find all possible instance of Button
public ArrayList<Button> getButtons() {
ArrayList<Button> buttons = new ArrayList<Button>();
ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
findButtons(viewGroup, buttons);
return buttons;
}
private static void findButtons(ViewGroup viewGroup,ArrayList<Button> buttons) {
for (int i = 0, N = viewGroup.getChildCount(); i < N; i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof ViewGroup) {
findButtons((ViewGroup) child, buttons);
} else if (child instanceof Button) {
buttons.add((Button) child);
}
}
}
Hope that help!
In this case ll is a LinearLayout and this search is only inside this one layout and will not recursively search the whole view tree. Something like this probably works. Did not test.
Vector<Button> buttons = new Vector<Button>();
for (int i=0; i < ll.getChildCount(); i++){
View v = ll.getChildAt(i);
if (v instanceof Button) {
buttons.add(v);
}
}
Button lastButton = buttons.lastElement();
I have to say it sounds like you are probably approaching the problem in a wrong way. This sounds like a very strange approach. Just out of curiosity, what are you trying to achieve?

Method to get all EditTexts in a View

can anyone help me with coding a method to get all EditTexts in a view? I would like to implement the solution htafoya posted here:
How to hide soft keyboard on android after clicking outside EditText?
Unfortunately the getFields() method is missing and htafoya did not answer our request to share his getFields() method.
EDIT
MByD pointed me to an error, thus making my answer almost identical to that of blackbelt. I have edited mine to the correct approach.
You could do a for-each loop and then check if each view is of the type EditText:
ArrayList<EditText> myEditTextList = new ArrayList<EditText>();
for( int i = 0; i < myLayout.getChildCount(); i++ )
if( myLayout.getChildAt( i ) instanceof EditText )
myEditTextList.add( (EditText) myLayout.getChildAt( i ) );
You could also, instead of having a list of EditTexts, have a list of ID's and then just add the id of the child to the list: myIdList.add( child.getId() );
To access your layout you need to get a reference for it. This means you need to provide an ID for your layout in your XML:
<LinearLayout android:id="#+id/myLinearLayout" >
//Here is where your EditTexts would be declared
</LinearLayout>
Then when you inflate the layout in your activity you just make sure to save a reference to it:
LinearLayout myLinearLayout;
public void onCreate( Bundle savedInstanceState ) {
super( savedInstanceState );
setContentView( R.layout.myLayoutWithEditTexts );
...
myLinearLayout = (LinearLayout) findViewById( R.id.myLinearLayout );
}
You then have a reference to your the holder of your EditTexts within the activity.
Here's a method I wrote to recursively check all EditText children of a ViewGroup, handy for a long sign-up form I had to do and probably more maintainable.
private EditText traverseEditTexts(ViewGroup v)
{
EditText invalid = null;
for (int i = 0; i < v.getChildCount(); i++)
{
Object child = v.getChildAt(i);
if (child instanceof EditText)
{
EditText e = (EditText)child;
if(e.getText().length() == 0) // Whatever logic here to determine if valid.
{
return e; // Stops at first invalid one. But you could add this to a list.
}
}
else if(child instanceof ViewGroup)
{
invalid = traverseEditTexts((ViewGroup)child); // Recursive call.
if(invalid != null)
{
break;
}
}
}
return invalid;
}
private boolean validateFields()
{
EditText emptyText = traverseEditTexts(mainLayout);
if(emptyText != null)
{
Toast.makeText(this, "This field cannot be empty.", Toast.LENGTH_SHORT).show();
emptyText.requestFocus(); // Scrolls view to this field.
}
return emptyText == null;
}
You can do it by calling View#getFocusables, which will return an arraylist of all focusable views in a View.
Then you can either check if they are EditTexts, with (instanceof) or act on all of them.
This Methods walks recursively through all ViewGroups and collects their TextViews. I use this to assign a new Color to all TextViews (even those embedded in predefined Widgets like Switch etc that make use of TextViews)
private HashSet<TextView> getTextViews(ViewGroup root){
HashSet<TextView> views=new HashSet<>();
for(int i=0;i<root.getChildCount();i++){
View v=root.getChildAt(i);
if(v instanceof TextView){
views.add((TextView)v);
}else if(v instanceof ViewGroup){
views.addAll(getTextViews((ViewGroup)v));
}
}
return views;
}
Get all Edit Text in any type of layout.
public List<EditText> getAllEditTexts(ViewGroup layout){
List<EditText> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
View v =layout.getChildAt(i);
if(v instanceof EditText){
views.add((EditText)v);
}
}
return views;
}

How to iterate through a view's elements

I have a view with radios, inputs and a button and when I click it, I want to check that all inputs contain information. How can I iterate through the view's elements in the activity and check if every textview meets the aforementioned requirement ? Thanks.
I've done something similar in some code I don't have with me at the moment, but from memory it should be something like this (assuming a parent view LinearLayout with an id of "layout"):
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
boolean success = formIsValid(layout);
public boolean formIsValid(LinearLayout layout) {
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v instanceof EditText) {
//validate your EditText here
} else if (v instanceof RadioButton) {
//validate RadioButton
} //etc. If it fails anywhere, just return false.
}
return true;
}
To apply the method by kcoppock recursively, you can change it to this:
private void loopViews(ViewGroup view) {
for (int i = 0; i < view.getChildCount(); i++) {
View v = view.getChildAt(i);
if (v instanceof EditText) {
// Do something
} else if (v instanceof ViewGroup) {
this.loopViews((ViewGroup) v);
}
}
}
If you are writing in Kotlin, Android Jetpack's Kotlin extensions (KTX) provide extension functions for iterating over a ViewGroup's children.
myViewGroup.forEach { ... }
myViewGroup.forEachIndexed { index, view -> ... }
Just add the dependency to your app. Check the link above to get the most up-to-date version.
implementation "androidx.core:core-ktx:1.2.0"
These extensions contains hoards of useful functions otherwise chalked up as boilerplate. Worth checking out now to save time in the future!
Your onClickListener supplies the View v object; use View rV = v.getRootView() to position yourself on the form. Then use rV.findViewWithTag( ... ) or rV.findViewByID(R.id. ... ) to locate your form elements.

Categories

Resources