findViewById in Fragment

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

    The method getView() wont work on fragments outside OnCreate and similar methods.

    You have two ways, pass the view to the function on the oncreate (what means you can only run your functions when the view is being created) or set the view as a variable:

    private View rootView;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_contatos, container, false);
    }
    
    public void doSomething () {
        ImageView thumbnail = (ImageView) rootView.findViewById(R.id.someId);
    }
    

提交回复
热议问题