【问题标题】:setContentView in fragment片段中的 setContentView
【发布时间】:2013-05-07 16:55:04
【问题描述】:

我正在尝试将 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 ?

【问题讨论】:

    标签: android android-fragments android-activity


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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;
      }
      

      另外,onCreateViewonCreate 之后调用,因此如果您尝试在onCreate 中使用findViewById,它将返回 null,因为还没有附加布局视图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-20
        • 1970-01-01
        • 2020-07-30
        相关资源
        最近更新 更多