How to access Fragment’s child views inside fragment’s parent Activity?

Note:

Directly accessing fragment’s views outside fragment is not a good idea. You should use fragment callback interfaces to handle such cases and avoid bugs. The following way works but it is not recommended as it is not a good practice.


If you want to access the TextView of Fragment inside its parent Activity then you should define a method inside your Fragment class like this:

public class MyFragment extends Fragment {

    TextView mTextView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container, false);
        mTextView = (TextView) view.findViewById(R.id.textView1);
        return view;
    }

    public void setTextViewText(String value){
        mTextView.setText(value);
    }


}

Now you can use this inside your Activity like this:

myFragment.setTextViewText("foo");

here myFragment is of type MyFragment.

If you want to access the whole TextView then you can define a method like this inside MyFragment.java:

public TextView getTextView1(){
    return mTextView;
}

By this you can access the TextView itself.

Hope this Helps. 🙂

Leave a Comment