findViewById in Fragment

后端 未结 30 2321
终归单人心
终归单人心 2020-11-21 06:39

I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. However, the findViewById<

30条回答
  •  终归单人心
    2020-11-21 07:41

    Inside Fragment class you will get onViewCreated() override method where you should always initialize your views as in this method you get view object using which you can find your views like :

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.findViewById(R.id.yourId).setOnClickListener(this);
    
        // or
        getActivity().findViewById(R.id.yourId).setOnClickListener(this);
    }
    

    Always remember in case of Fragment that onViewCreated() method will not called automatically if you are returning null or super.onCreateView() from onCreateView() method. It will be called by default in case of ListFragment as ListFragment return FrameLayout by default.

    Note: you can get the fragment view anywhere in the class by using getView() once onCreateView() has been executed successfully. i.e.

    getView().findViewById("your view id");
    

提交回复
热议问题