Reputation: 126
I Have a custom activity that load graphics from an XML file, where i have a lot of Buttons, Images and Text.
For implementation i want to use android classes like ImageButton
, TextView
and ImageView
.
I have thinking to use a List<View>
for looping all View
objects and inflating into a RelativeLayout
.
Is better a List<View>
or List<ImageButton>
, List<TextView>
and List<ImageView>
?
Method implementation in ImageButton
or ImageView
(Like onClick
or some other event), is lost when i convert it to a View
object?
ImageButton imageButton = new ImageButton(getContext());
//Implementation of methods and events...
List<View> list = new ArrayList<View>;
list.add(imageButton);
Upvotes: 0
Views: 99
Reputation: 11651
You biggest doubt here is
Method implementation in ImageButton or ImageView (Like onClick or some other event), is lost when I convert it to a View object?
NO, this does not happen.
Consider two classes
class Parent{
void big(){}
}
and
class Child extends Parent{
void small(){}
}
If you say
Child c = new Child();
then you can use
c.big();
as well as c.small();
but if you say
Parent c = new Child();
you are allowed to use
c.big();
But for calling small()
inside Child
class
you need to cast it
Child ch = (Child)c;
ch.small();
Now if there a number of subclasses, each with different methods available to them which
like Child1
with small1()
and Child2
with small2()
and so on then you can use instanceof
for casting
like
if(ch1 instanceof Child1)
{
Child1 c1 = (Child1)ch1;
c1.small1();
}
if(ch2 instanceof Child2)
{
Child2 c2 = (Child2)ch2;
c2.small2();
}
Upvotes: 1
Reputation: 2005
The list only holds references of your components. If you create an ImageButton
for exmaple, set a click listener and add it to the List<View>
, nothing will get lost. Only thing is you won't know each view's actual type.
To get the true class of a generic View
you can use multiple if
statements that check all of your component types, like:
if (view instanceof ImageButton) {
ImageButton imageButton = (ImageButton)view;
}
instanceof checks if an object is of a specific class or extends it. So make sure you first check for ImageButton
before ImageView
for example, because its a descendant of the class.
Upvotes: 1