Question

Hi I am working with android.I had tried to inflate a layout into the fragment, but it shows error in the code "method getLayoutInflater() is undefined for the class". how can I access layout within the fragments ??? please help me I am new to android .Thanks

here is my code

        View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
         listView1.addHeaderView(header); 
Was it helpful?

Solution

getLayoutInflater() is a method of Context

use getActivity().getLayoutInflater()... valid after onAttach() call back is called in Fragment

OTHER TIPS

I'm assuming you are calling this inside of an Activity. Try doing

LayoutInflater li = (LayoutInflater) getApplicationContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View header = li.inflate(R.layout.listview_header_row, null);

If, on the other hand, you're calling this from a custom adapter, you will need to pass either the LayoutInflater, or the Context variable to the adapter.

Adapter:

class MyCustomAdapter{
LayoutInflater li;
    public MyCustomAdapter (LayoutInflater li) {
        layoutInflater = li;
    }
    //...
}

Activity:

public class MyActivity extends Activity {
//...
    public void onCreate() {
        MyCustomAdapter adapter = new MyCustomAdapter((LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        listView.setAdapter(myCustomAdapter);
    }
//...
}

Try this:

View view = LayoutInflater.from(getActivity()).inflate(
                R.layout.your_layout, null);

Full code

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = LayoutInflater.from(getActivity()).inflate(
            R.layout.your_layout, null);
    return view;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top