0

This is the only way I can find but it seems hacky:

public View getViewByIdFromLayout(int id) {
    for (int i = 0; i < layout.getChildCount(); i++) {
        View v = layout.getChildAt(i);
        if (v.getId() == id)
            return v;
    }
    return null;
}

Is there a better way to do this? These views were created programmatically, not via xml, and the views' ids will be unique in a given layout but may be reused in other layouts.

1
  • Can't you just hold on to the reference of the view and use it later?
    – Szymon
    Sep 19, 2013 at 23:52

2 Answers 2

3

You can still use findViewById() as long as you've given it an ID. Just make sure to call findViewById() on the layout for which the ID is unique.

1
  • Argh, my eyes must have glazed over because I looked for that and couldn't find it on the list of methods for layouts. Maybe I was looking for getViewByID or something.
    – DevOfZot
    Sep 19, 2013 at 23:54
0

You should change

 if (v.getId() == id)
        return v;

to

 if (v.getId().equals(id))
        return v;
2
  • 2
    .equals() compares String values. == is the correct operator for comparing int equality
    – codeMagic
    Sep 20, 2013 at 0:04
  • 2
    more generally, .equals() compares Objects
    – Droidman
    Sep 20, 2013 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.