Search code examples
androidviewviewgroup

Android colored view containing textviews


Ive made a program which has a view in the top op the window (right under the title bar). According to what is goin on in the program, the color of the view will change.

This works just fine.

Now my problem is: I want 2 textviews inside it, next to each other. So probably: View, Tablelayout, tablerow, textview, textview, tablerow end, tablelayout end, view end.

But this does not seem to work. It gave me the error "Java.lang.RuntimeException: Unable to start activity ComponentInfo" and "View can not be cast to viewgroup".

Nowhere in the java code do i touch any of the new views in the xml code, the only java that touches that XML, is TopView = (View)findViewById(R.id.TopView); and TopView.setBackgroundColor(Color.GREEN ); Topview is the outer view, and works perfectly without anything inside it.

This is the XML code

    ...
<View
        android:id="@+id/TopView"
        android:layout_width="fill_parent"
        android:layout_height="20dp" 
        android:background="#8E8E8E" >



        <TableLayout
                android:id="@+id/tableTrolo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TableRow
                    android:id="@+id/TableRow000"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="left"
                    android:gravity="left"
                    android:orientation="vertical" >


            <TextView
                        android:id="@+id/lbl1"
                        android:layout_width="120dp"
                        android:layout_height="wrap_content"
                        android:text="Vare :"
                        android:textSize="22dp" />

                    <TextView
                        android:id="@+id/lbl2"
                        android:layout_width="180dp"
                        android:layout_height="wrap_content"
                        android:text="du grim" />

            </TableRow>
            </TableLayout>


    </View>
...

Solution

  • You can not have child-views inside a View.

    A View is always the leaf node in a layout hierarchy.

    1.Re-write the 1st line of your xml-layout as:

    <LinearLayout
        android:id="@+id/TopView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:background="#8E8E8E">
    

    2.Change corresponding Java code as below:

    TopView = (LinearLayout)findViewById(R.id.TopView);