片段中的setContentView

时间:2013-05-07 16:55:04

标签: android android-fragments android-activity

我正在尝试将Activity转换为片段。 setContentView上的错误标记。

这是我的代码

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){
        }
    });
}

如何转换setContentView?

2 个答案:

答案 0 :(得分:6)

这不应该进入onCreate,你必须覆盖onCreateView

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

答案 1 :(得分:2)

bclymer对你提出的问题有正确的答案,我只想补充一点,你也可以在这个方法中照顾findViewById,如下:

@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;
}

此外,在onCreateView之后调用onCreate,因此如果您尝试在findViewById中使用onCreate,则会返回null,因为尚未附加布局视图。< / p>