findViewById 中的错误尝试了一切

Error in findViewById tried everything

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

带按钮的选项卡式视图的此 ID

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/documents");

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myDir.mkdirs();
    EditText edit = (EditText)findViewById(R.id.editText);
    String edt = edit.getText().toString();
    File file = new File (myDir,edt);
}

这是为了在 android 的外部存储中保存一个文件夹,我正在从用户那里输入文件夹名称并使用我正在使用这个语句 ↓

EditText edit = (EditText)findViewById(R.id.editText);
String edt = edit.getText().toString();

但是 findViewById 报错

方法 findViewById() 未在 class Fragment 中实现。该方法是为 ActivityView

实现的

所以,尝试以下更改:

public void onCreate(Bundle savedInstanceState) {
    ....
    EditText edit = (EditText) getActivity().findViewById(R.id.editText);
    ....
}

更新

正如下面评论的那样,您不能依赖 findViewById()onCreate 方法中从父 Activity 查找视图。这也在DOCS:

中标出

Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, see onActivityCreated(Bundle).

这样,如果您的 EditTextR.layout.fragment_fingerp

的一部分

你可以这样做:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_fingerp, container, false);

    EditText edit = (EditText) rootView.findViewById(R.id.editText);
    String edt = edit.getText().toString();
    File file = new File (myDir,edt);

    return rootView;
}

或者将您的代码从 onCreate() 移动到 onActivityCreated :

public void onActivityCreated (Bundle savedInstanceState) {
    ...              
    EditText edit = (EditText) getActivity().findViewById(R.id.editText);
    ...
}

将您的代码从 onCreate 移至 onViewCreated,它专门用于 Fragment 生命周期回调。