错误:找不到符号方法findviewbyid

时间:2016-05-14 08:23:19

标签: android fragment findviewbyid

我有一个带有listView的2个片段的tabLayout,我想用Json从URLConnection加载内容但是在Fragment.java文件中我发现错误:无法解决方法&#39 ; 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);
    }


} 

3 个答案:

答案 0 :(得分:1)

您应该使用findViewById类的View。这样您就可以为ListView

创建一个全局变量
ListView canteenList;

然后在onViewCreated初始化您的canteenList

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

答案 1 :(得分:1)

stack overflow

上关注此答案
 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);
    }

答案 2 :(得分:0)

您必须创建一个全局变量

  

查看mainContent;

之后在 onCreateView 中充气时

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

最后使用引用主要内容,你可以 findViewById 这样

  

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