So if I were to have a LinearLayout and had several children Views inside of it, say like a couple of Buttons a TextView and a CheckBox, using the LinearLayout's getChildAt(x) I would then get an unspecified View. To note, I'm not using an xml in this so it's all done programatically.
public class CustomViewClass extends LinearLayout {
private Context context;
public CustomViewClass (Context context) {
super(context);
this.context = context;
setOrientation(LinearLayout.VERTICAL);
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
setBackgroundColor(Color.DKGRAY);
// Code which adds Buttons and such to the LinearLayout
getChildAt(1)
}
}
The getChildAt(1), is there anyway that I can find out what kind of View it is, whether it's a Button or a TextView or whatever progamatically?
One way to do this is to call getClass. This will get you a Class object representing the type of view.
For example:
Class clazz = getChildAt(1).getClass();
After you have the class, you can do all kinds of things with it. e.g. get the name:
System.out.println(clazz.getName());
Now you know what kind of view it is.
Another way is to use the instanceof operator. Here's an example:
if (getChildAt(1) instanceof TexView) {
// getChildAt(1) is a TextView or an instance of a subclass of TextView
}