findViewById not recognised in ListFragment [duplicate]

寵の児 提交于 2019-12-04 02:25:56

问题


Possible Duplicate:
findViewById in fragment android

I am currently working on android project and trying to get fragments working. The fragment part is working but I'm trying to control UI components, on a standard activity I can use something like

TextView txtMyTextBox = (TextView)findViewById(R.id.my_text_box)

I am extending the class by ListFragment but when why I try the same code as above I get the following error

The method findViewById(int) is undefined

Why doesn't this work. Thanks for any help you can provide.


回答1:


That method is not defined in the Fragment class which is where I assume you're calling it. You have to use it on the View that the Fragment is showing. This is the same view that you return in onCreateView() and you can retrieve it by getView(). Thus, TextView txtMyTextBox = (TextView)getView().findViewById(R.id.my_text_box) should work.




回答2:


When you use fragments, you should override the onCreateView method.

Here is an exemple :

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        View v = inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, null);

        TextView txtMyTextBox = (TextView)v.findViewById(R.id.my_text_box)

        return v;
    }


来源:https://stackoverflow.com/questions/12324623/findviewbyid-not-recognised-in-listfragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!