findViewById in Fragment

后端 未结 30 2262
终归单人心
终归单人心 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:35

    Inside Fragment class we get onViewCreated() override method where we should always initialize our views because in this method we get view object. Using this object we can find our views like below:

    class MyFragment extends Fragment {
        private ImageView imageView;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.my_fragment_layout, container, false);
        }
    
        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
    
            //initialize your view here for use view.findViewById("your view id")
            imageView = (ImageView) view.findViewById(R.id.my_image);
        }
    }
    

提交回复
热议问题