IllegalArgumentException:尝试setView时,找不到片段id的视图

时间:2018-03-10 08:40:32

标签: android fragment findviewbyid setcontentview

它说IllegalArgumentException:当我尝试setview时,没有找到片段id的视图。我知道问题出在第3和第4行。它的News.java文件新闻是一个片段。

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setContentView(R.layout.fragment_news);
        listView = (ListView) getActivity().findViewById(R.id.list);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

1 个答案:

答案 0 :(得分:0)

Fragment.java文件如下所示:

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_news, container, false);
        //ButterKnife.bind(this, view);

       init(view);

        return view;
    }

之后的init方法类型代码:

private void init(View view){

listView = (ListView) view.findViewById(R.id.list);

    feedItems = new ArrayList<FeedItem>();

    listAdapter = new FeedListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);
    }

您也不要忘记extends Fragment