Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android instanceof detecting all widgets?

I'm trying to set a font across all TextView's by iterating through the LinearLayout's views and using instanceof.

The form currently consists of 4 TextView's and one Button.

The below code is detecting all Views, even the Button as a TextView?

    /* Set fonts */
    LinearLayout ll = (LinearLayout) findViewById(R.id.ll_screenincourse_wrapper);
    for (int i = 0; i < ll.getChildCount(); i++) {          
        View v = ll.getChildAt(i);          
        if (v instanceof TextView) {
            ((TextView) v).setTypeface(Fonts.get3dDumbFont(this));
        }
    }

If I log each view's class name it returns the TextView and the Button so I know the correct controls are being picked up.

The problem is the Button and TextView's fonts are being set, and I only want the TextView's.

I have found a work around and that is to do the following but am intrigued as to why the above code does not work as expected.

    /* Set fonts */
    LinearLayout ll = (LinearLayout) findViewById(R.id.ll_screenincourse_wrapper);
    for (int i = 0; i < ll.getChildCount(); i++) {          
        View v = ll.getChildAt(i);          
        if (v.getClass().getName().contains("TextView")) {
            ((TextView) v).setTypeface(Fonts.get3dDumbFont(this));
        }
    }

Is it because both Button and TextView are of type View? If so, what would be the correct way about doing this?

Any help appreciated, thanks. Ricky.

like image 608
Ricky Avatar asked Jul 03 '26 07:07

Ricky


1 Answers

Actually, Button is a subclass of TextView! That's why you see it as a TextView (it is also a TextView).

http://developer.android.com/reference/android/widget/Button.html

public class Button extends TextView

You could make a second if instanceof to exclude Buttons or use

if (v.getClass() == TextView.class)

But this won't match any other subclasses of TextView (if you use them).

like image 61
Pedro Loureiro Avatar answered Jul 04 '26 21:07

Pedro Loureiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!