My main.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Since the root element is a LinearLayout, which extends ViewGroup, why does main.xml get turned into a View instead of a ViewGroup? For example, in my main Activity class, I try to get the number of subviews that the LinearLayout contains like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup vg = (ViewGroup) findViewById(R.layout.main);
Log.v("myTag", "num children: " + vg.getChildCount());
but it crashes when i call vg.getChildCount().
What is the right way of doing it?
findViewByIdis supposed to take the ID of a view defined inside a layout XML file, not the id of the file itself. Once you have inflated the view, either manually or viasetContentView, you could get the Layout with it, if you had done it this way:By:
Note the addition of an
android:idattribute and the use of the matchingR.idvalue in thefindViewByIdcall. It’s the same usage as described in the Dev Guide. You should then be able to safely cast the result into aViewGrouporLinearLayout.If, by some chance, you want to load the main view separately, e.g. as a subview, use
getLayoutInflater().inflate(...)to build and retrieve it.