views:

72

answers:

1

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?

+4  A: 

findViewById is 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 via setContentView, you could get the Layout with it, if you had done it this way:

<?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"
    android:id="@+id/mainlayout"
>
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
/>
</LinearLayout>

By:

ViewGroup vg = (ViewGroup) findViewById(R.id.mainlayout);

Note the addition of an android:id attribute and the use of the matching R.id value in the findViewById call. It's the same usage as described in the Dev Guide. You should then be able to safely cast the result into a ViewGroup or LinearLayout.

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.

Walter Mundt