在Fragment中使用findViewById

Mav*_*ven 2 android android-fragments

我正在创建一个新的Tab界面,对于每个选项卡,我都有以下功能:

public class ClassViewFragment extends Fragment {
    ListView classListView = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.class_view, container, false);

        classListView = (ListView) findViewById(R.id.classList);

        return rootView;
    }
}
Run Code Online (Sandbox Code Playgroud)

但我cannot resolve method findViewById也在另一个地方,我也无法使用runOnUiThread和获取Error:(88, 29) error: cannot find symbol method runOnUiThread(<anonymous Runnable>)

我知道如果我的课程扩展了,这些工作正常,Activity但是它是一个标签片段,那我该如何使用这个功能呢?

tyc*_*czj 6

你需要

classListView = (ListView) rootView.findViewById(R.id.classList);
Run Code Online (Sandbox Code Playgroud)

因为这是你关心的观点

得到runOnUiThred你需要做的 getActivity().runOnUiThread


Div*_*a Y 6

你需要使用视图引用findViewById,

public class ClassViewFragment extends Fragment {
    ListView classListView = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.class_view, container, false);

        classListView = (ListView) rootView .findViewById(R.id.classList);

        return rootView;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于runOnUiThread,可能是从不同线程修改Android视图的副本

用它来的,

activity.runOnUiThread(new Runnable());
Run Code Online (Sandbox Code Playgroud)