Adam Praiswater
Adam Praiswater

Reputation: 93

How to reference a view from fragment Android

Why won't this let me reference the EditText? i tried passing activity and it didn't work.

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class HomeFragment extends Fragment {

    public HomeFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        EditText savedata = (EditText).getActivity(),findViewById(R.id.savebtn);
        return rootView;
    }
}

Upvotes: 4

Views: 3966

Answers (2)

joselufo
joselufo

Reputation: 3415

You can't pass reference from Activity.

Change this:

  EditText savedata = (EditText)rootView .findViewById(R.id.savebtn);

Upvotes: 1

Raghunandan
Raghunandan

Reputation: 133560

Change this

 EditText savedata = (EditText).getActivity(),findViewById(R.id.savebtn);

to

  EditText savedata = (EditText)rootView.findViewById(R.id.savebtn);

Assuming the edittext belongs to fragment_home.xml.

You can also initialize in onActivityCreated using getView().findViewById(id)

Note:

The fragment can access the Activity instance with getActivity() and easily perform tasks such as find a view in the activity layout:

View listView = getActivity().findViewById(R.id.list);

Upvotes: 4

Related Questions