How do I “findViewById” with fragments?

我是研究僧i 提交于 2019-11-27 09:08:20

The problem is in your onCreateView method.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
     // Inflate the layout for this fragment
     View v = inflater.inflate(R.layout.fragment_complaints, container, false);

     //i added
     recipient = (EditText) v.findViewById(R.id.recipient);

     [...]

     return v;
}

See the difference? You have to call findViewById on actual View object in case of Fragments.

And the problem with Toast you have is because you are passing worng object as first parameter. You need Context and you are passing Fragment. Fragment is not a Context but luckly for you Activity is so, you have to construct your Toast like this:

Toast.makeText(ComplaintsFragment.this.getActivity(), "No email client installed.",
           Toast.LENGTH_LONG).show();

Note that getActivity() call.

Andre Classen

So your onCreateView method should look like:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.fragment_complaints, container, false);
recipient = (EditText) rootView.findViewById(R.id.recipient);
subject = (EditText) rootView.findViewById(R.id.subject);
body = (EditText) rootView.findViewById(R.id.body);
Button sendBtn = (Button) rootView.findViewById(R.id.sendEmail);
sendBtn.setOnClickListener(new View.OnClickListener() {

    public void onClick(View view) {
        sendEmail();
        // after sending the email, clear the fields
        recipient.setText("");
        subject.setText("");
        body.setText("");
    }
});
return rootView;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!