FindViewbyID with fragments

后端 未结 1 1793
一个人的身影
一个人的身影 2021-01-25 10:38

I have this problem with fragments.. I wanted to add a drawer menu in my app and than work with fragments. I have this code, and when i putted the fragments \"findviewbyid\" did

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 10:52

    The Fragment is not a Activity which means you can not use activity methods or it's lifecycle. This means you cant find views in the onCreate() method of a Fragment and you can not use findViewById on it either.

    This is the Android lifecycle https://stackoverflow.com/a/36340059/4467208

    and to adjust your code according to that, move your findViews into onCreateView() like this

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmentLayout, container, false);
        nome = (EditText) view.findViewById(R.id.nome);
        return view;
    }
    

    And so on.

    0 讨论(0)
提交回复
热议问题