Get view of Fragment from FragmentActivity

Drastamat picture Drastamat · Jun 10, 2013 · Viewed 68.4k times · Source

I have a FragmentActivity where I add a Fragment. Depending on some situation, I want to access Buttons from that fragment's layout and change click listeners of them.

What I do is:

View view = myFragment.getView();
Button myButton = (Button) view.findViewById(R.id.my_button);
myButton.setOnClickListener(new MyClickListener());

But the view variable is always null.

How can I get the view of the activity?

Answer

Jarvis picture Jarvis · Jun 10, 2013

If you want to access your component and set some data, I suggest you to make a method inside the fragment like this:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class DetailFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.details, container, false);
        return view;
    }


    public void setSettings(){
        Button button = (Button) getView().findViewById(R.id.my_button);
        button.setOnClickListener(new MyClickListener());
    }
}