Android Layout Inflater not working?

Sam*_*tty 2 java xml android-layout layout-inflater

I have an inflater in my main java class, mainly because I want to be able to 'findViewById' in a layout other then the one set in 'setContentView' (activity_main.xml).

Since I'm new to Android dev and Java in general, I thought I could do this with a layout inflater. Anyway, the layout I'm trying to inflate a layout named "box_middle".

This is my code where I create the inflater (and try to use it).

LayoutInflater inflater = (LayoutInflater)this.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.box_middle, null);

    drawerGrid = (GridView) view.findViewById(R.id.content);
Run Code Online (Sandbox Code Playgroud)

I am initialising "drawerGrid" like this (public)

 GridView drawerGrid;
Run Code Online (Sandbox Code Playgroud)

The end result is nothing shows up where the GridView in the XML code is.

Here is the XML code (box_middle)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<!-- Card visible layout -->
<LinearLayout
    android:id="@+id/card_main_layout"
    style="@style/card.main_layout"
    android:orientation="vertical"
    android:layout_width="142dip"
    android:layout_height="150dip"
    android:background="#ffff0c00">

    <GridView
        android:id="@+id/content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"/>

</LinearLayout>

<!-- Compound view for Shadow
       If you want to customize this element use attr card:card_shadow_layout_resourceID -->
<it.gmariotti.cardslib.library.view.component.CardShadowView
    style="@style/card.shadow_outer_layout"
    android:id="@+id/card_shadow_layout"
    android:layout_width="150dip"
    android:layout_height="wrap_content"/>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

Thanks.

BTW I'm using Android Studio and this library.

小智 5

You use

LayoutInflater inflater = (LayoutInflater)this.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.box_middle, null);
Run Code Online (Sandbox Code Playgroud)

to inflate the view, but you don't attach it to the window. Don't forget to use this.setContentView(view);

All the code should be :

LayoutInflater inflater = (LayoutInflater)this.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.box_middle, null);
this.setContentView(view);`
Run Code Online (Sandbox Code Playgroud)