10

Can I load layout from xml during onCreateView call, I tried:

  • setLayoutResource(R.layout.test);
  • setWidgetLayoutResource(R.layout.test);

it crashes and I don’t know what to return a ViewGroup parent from a method arguments? I also tried:

  • View view = View.inflate(getContext(), R.layout.test, parent) but it didn’t worked as well.

I named root layout widget_frame but it didn’t helped

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" 
 android:padding="1dp" android:clickable="false" android:id="@+id/widget_frame">
 <LinearLayout ....

Could you tell me what I’m doing wrong or point me to some working example. Thanks

Update

Below is a woking solution on how to inflate above layout:

    LayoutInflater inflater =  (LayoutInflater)getContext().
                              getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View view = inflater.inflate(R.layout.test, parent, false);
michael
  • 3,250
  • 10
  • 43
  • 58
  • Great! this worked for me too! But the documentation was a little confusing as it said: "The default behavior is to inflate the main layout of this Preference (see setLayoutResource(int)." I just did not get what the purpose of calling setLayoutResource could be, as we clearly need to return a View and setLayoutResource returns void. – Bilthon Dec 17 '11 at 16:24
  • If you want to set the layout with `setLayoutResource` your view's id should be `"@android:id/widget_frame"` not `"@+id/widget_frame"`. – GDanger Aug 19 '15 at 20:09

2 Answers2

2

If you are using onCreateView I guess you are either using a fragment or extending a View. Anyway check this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.your_layout, container);
}
Shekhar Chikara
  • 3,786
  • 2
  • 29
  • 52
Daniel López Lacalle
  • 6,715
  • 3
  • 25
  • 23
0

If you are inflating a layout you should do something like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     return inflater.inflate(R.layout.your_layout, null);
}
Tudor Timi
  • 7,453
  • 1
  • 24
  • 53
Adarsh Gowda
  • 196
  • 2
  • 13