setContentView in fragment

15,959

Solution 1

This shouldn't go in onCreate, you must override onCreateView

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {             
    View rootView = inflater.inflate(R.layout.activity_googlev2, container, false);
    return rootView;
}

Solution 2

bclymer has the correct answer to what you are asking, I just would like to add that you can also take care of findViewById inside that method like such:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {             
    View rootView = inflater.inflate(R.layout.activity_googlev2, container, false);
    textView = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextView1);
    return rootView;
}

Also, onCreateView is called after onCreate so if you try to use findViewById in your onCreate it will return null since there is no layout view attached yet.

Share:
15,959
Tai Dao
Author by

Tai Dao

I'm a self employed android software architect, certified scrum master and product owner. free to ask. I'm glad to help you :)

Updated on June 14, 2022

Comments

  • Tai Dao
    Tai Dao almost 2 years

    I'm trying to convert a Activity to fragment. The error mark on setContentView.

    here is my code

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_googlev2);
        Init();
        addMarkersToMap();
        yStart = 21.102918;
        yEnd = 20.960798;
        xStart = 105.772762;
        xEnd = 105.900650;
        xNow = xStart;
        yNow = yStart;
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line);
        textView = (AutoCompleteTextView) getView().findViewById(R.id.autoCompleteTextView1);
        textView.setThreshold(3);
        adapter.setNotifyOnChange(true);
        textView.setAdapter(adapter);
        textView.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count){
                autoCount = count;
                autoS = s;
                if(autoCount % 3 == 1) {
                    stCommand = "AutoCompleteTextView";
                    lp = new ExecuteTask();
                    lp.execute();
                }
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after){ // TODO Auto-generated method stub
            }
            public void afterTextChanged(Editable s){
            }
        });
    }
    

    how to convert that setContentView ?