Drastamat Drastamat - 1 year ago 77
Android Question

Get view of Fragment from FragmentActivity

I have a

where I add a
Depending on some situation, I want to access
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
variable is always

How can I get the view of the activity?

Answer Source

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 {

    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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download