0

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

Programmer
  • 15
  • 4

1 Answers1

0

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.

Karakuri
  • 38,365
  • 12
  • 84
  • 104