error: cannot find symbol method findviewbyid

error: cannot find symbol method findviewbyid

我有一个带有 listView 的 2 个片段的 tabLayout 的应用程序,我想使用 Json 从 URLConnection 加载内容,但在 Fragment.java 文件中我收到错误:can' t 解析方法 'findViewByID(int)'.

   public class Fragment1 extends Fragment implements URLConnectionResponse {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CanteenProvider canProv = new CanteenProvider();
        canProv.delegate = this;
        canProv.getDishes(getActivity().getApplicationContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.activity_canteen_tab_mensa, container, false);
    }

    @Override
    public void processFinish(List<?> output) {
        ListView canteenList = (ListView) findViewById(R.id.mensalistView);
        ArrayList<Dish> canteenItemContent = new ArrayList<Dish>();
        canteenItemContent = (ArrayList<Dish>)output;

        CanteenListAdapter canteenAdapter = new CanteenListAdapter(canteenItemContent, this);
        canteenList.setAdapter(canteenAdapter);
    }


} 

您必须创建一个全局变量

View mainContent;

然后在onCreateView中膨胀的时候像这样

mainContent = inflater.inflate(R.layout.activity_canteen_tab_mensa, container, false);
return mainContent;

最后,通过 mainContent 的引用,您可以 findViewById 像这样

ListView canteenList = (ListView) mainContent.findViewById(R.id.mensalistView);

您应该使用 findViewByIdView class。所以你可以为你的ListView创建一个全局变量:

ListView canteenList;

然后在您的 onViewCreated 中初始化您的 canteenList

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        canteenList = view.findViewById(R.id.mensalistView);
    }

上关注此答案
 private ListView canteenList=null;
  private View view = null;
 @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_canteen_tab_mensa, container, false);
        canteenList = (ListView)view.findViewById(R.id.mensalistView);
        return view;
    }

    @Override
    public void processFinish(List<?> output) {

        ArrayList<Dish> canteenItemContent = new ArrayList<Dish>();
        canteenItemContent = (ArrayList<Dish>)output;

        CanteenListAdapter canteenAdapter = new CanteenListAdapter(canteenItemContent, view.getContext());
        canteenList.setAdapter(canteenAdapter);
    }