How to iterate through a view's elements - android

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.

Related

How to make a group of views editable

I have a layout in which there are spinners, editText and checkboxes. There two modes:
1- edit all views (edit mode)
2- view (non edit mode)
But I don't want to do it for each view . Is there any way to set editable true or false?
This method will enable/disable all widgets of your parent layout.
public void enableAllView(ViewGroup rootView, boolean state) {
for (int i = 0; i < rootView.getChildCount(); i++) {
View childAt = rootView.getChildAt(i);
if (childAt instanceof ViewGroup ) {
enableAllView((ViewGroup) childAt, state);
} else {
if (childAt instanceof EditText) {
EditText child = (EditText) childAt;
child.setEnabled(state);
child.setFocusable(state);
} else if (childAt instanceof Spinner) {
Spinner child = (Spinner) childAt;
child.setEnabled(state);
child.setFocusable(state);
} else if (childAt instanceof CheckBox) {
CheckBox child = (CheckBox) childAt;
child.setEnabled(state);
child.setFocusable(state);
}
}
}
}
call this method like this--
enableAllView(rootView, true); // in case of edit(enable)
enableAllView(rootView, false); // in case of view(disable)
//rootView is a view in which your spinners/editText/checkbox are availabe.
in edit mode use this in every view
yourView.setEnabled(true);
in read mode use this
yourView.setEnabled(false);
The simple way is to create a set of such views manually:
val editableViews: Set<View> = setOf(v1, v2, v3)
and use it:
editableViews.forEach { it.enabled = isEditMode }
If you have a complex layout you may add dynamic initialization:
private fun getAllViews(
view: View,
set: MutableSet<View>,
filter: (view: View) -> Boolean = {true}
){
val viewGroup = view as? ViewGroup
if (viewGroup != null) {
for (i: Int in 0 until viewGroup.childCount) {
val child = viewGroup.getChildAt(i)
getAllViews(child, set)
}
} else {
if (filter()) {
set.add(view)
}
}
}
initialize it in onViewCreated or in onCreate
val views = mutableSetOf<View>()
getAllViews(root, views) {
it is Spinner || it is EditText || it is Checkbox
}
editableViews = views
It collects all required views, so you may make them enabled or disabled. But you should note, that this variant is not so flexible and you should prefer just the first one. (In case any exception you have to exclude some)

android - How to check if TextView is present in the layout?

I have two different layouts, say layout_1.xml & layout_2.xml. Both layouts have same elements inside it, but layout_2.xml has an additional TextView.
Only one layout will be called according to my needs. I want to perform a check if the textView is available in the layout.
If the TextView is available, it should perform textView.setText(), else the other layout will be called.
Please refer the code below:
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModel singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
Picasso.with(mContext).load(singleItem.getUrl()).into(holder.itemImage);
if (holder.lblDescription.getVisibility() == View.VISIBLE){
holder.lblDescription.setText(singleItem.getDescription());
}
}
The TextView holder.lblDescription is in layout_2.xml, but is not present in layout_1.xml.
Therefore, layout_2.xml is running with ease, but when it calls layout_1.xml its giving me this error Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference.
I know, the check I am performing is wrong. So, I need help in this.
Thanks in advance!
Well you are getting a null pointer exception because lblDescription isn't bound to anything in layout_1.xml where it isn't present. So basically what you can do is you can check
if(hold.lblDescription != null){
holder.lblDescription.setText(singleItem.getDescription());
}
instead of
if (holder.lblDescription.getVisibility() == View.VISIBLE){
holder.lblDescription.setText(singleItem.getDescription());
}
/**
* check textview is present or not
*
* #param group : parent layout id
*/
public boolean isTextViewPresent(ViewGroup group)
{
int count = group.getChildCount();
View v;
for (int i = 0; i < count; i++)
{
v = group.getChildAt(i);
if (v instanceof TextView)
{
return true;
} else if (v instanceof ViewGroup)
isTextViewPresent((ViewGroup) v);
}
return false;
}

Android Code does not work / 2 questions

Hello can anybody tell me why this code give me error and crash my app?
This happens only when 'reset((View) child);' is added at the end
What I want to do is when I click a Button with onClick:reset, It will apply a kind of reset to only Images and textviews inside a LinearLayout which has more types of childrens
public void reset(View v) {
LinearLayout items = (LinearLayout) findViewById(R.id.itemsToSearch);
for (int i = 0; i < items.getChildCount(); i++)
{
Object child = items.getChildAt(i);
Context context = getApplicationContext();
CharSequence text = child.toString();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
if (child instanceof ImageView)
{
((ImageView) child).setVisibility(View.INVISIBLE);
}
else if (child instanceof TextView)
{
((TextView) child).setTextColor(Color.parseColor("#98868A"));
}
else if(child instanceof ViewGroup)
{
reset((View) child);
}
}
}
and the other question is that my app works with FragmentPagerAdapter, How can I do for example if I click a Button in Frag#1 it will change a text inside Frag#3 which is currently not shown?, For me it always crash, As I see it is because Frag#3 or whatever other frag which is off screen is not yet loaded on screen and because of that it doesnt fint the specified ID
Thank You
Your reset method is broken. You are not using the view that is passed as an argument to the method, you are always searching for the same LinearLayout. Your code should look like this:
public void reset(ViewGroup viewGroup) {
final int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof ImageView) {
((ImageView) child).setVisibility(View.INVISIBLE);
} else if (child instanceof TextView) {
((TextView) child).setTextColor(Color.parseColor("#98868A"));
} else if(child instanceof ViewGroup) {
// recursive call
reset((ViewGroup) child);
}
}
}
Regarding your other issue, only the current fragment and the ones to either side (within the offscreen page limit, which by default is 1) are actually loaded and in a state where you can manipulate their views. You will need to store some data somewhere and refer back to that data when the page you want (Fragment #3 in your example) is instantiated and you start loading data into it.

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;
}

Getting information from RadioButtons and Checkboxes

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()

Categories

Resources