Reputation: 412
package net.example.view;
class StatusBar extends View { ... }
I use it in my layout as following:
<net.example.view.StatusBar .../>
I must find it by it's type(class), I mean something like:
myActivityInstance.findViewsByClass(StatusBar.class) // returns View[]
Is it possible? If not, what is the better approach to find an element without having to use findViewById()?
Thanks.
Upvotes: 0
Views: 280
Reputation: 46856
I don't think activity has a method that will return an array of Views to you based on class type. You could create and add them to your layout dynamically if you want to get an array of them without using findViewById() something like this:
mLayout = (LinearLayout)findViewById(R.id.mLayout);
StatusBar[] mBars = new StatusBar[10];
for(int i = 0; i < mViews.length; i++){
mBars[i] = new StatusBar(yourActivity.this);
mLayout.addView(mBars[i]);
}
That would give you an array full of StatusBar objects that have all been added to your layout. (You could make the array of type View if you wanted also).
If you are wanting to define all of your views in XML I don't think there is a way that you can avoid using findViewById() in a loop similar to this to get an array full of references to all of them. For this method you'd probably have to create an array of ints that is the same size that contains all of the resIDs of your views
ids[0] = R.id.mStatusBar1;
ids[1] = R.id.mStatusBar2;
etc.
Upvotes: 0
Reputation: 73484
If you can't use the id and your content view is some kind of ViewGroup you can iterate over the children.
ViewGroup vg = (ViewGroup) activity.getContentView();
for(int i=0; i<vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
if(v instanceof StatusBar) {
// do something interesting.
}
}
Also if you know the specific index you can call getChildAt(index)
directly.
Upvotes: 2