Johnny Broberg
Johnny Broberg

Reputation: 196

How to get Button click from Fragments

I got a Fragment that need to take a buttonclick.

Problem is that the click it going to the MainActivity hosting all fragments and not to the Fragment itself. I have tried Loging it and nothing shows in the logs when i click the button.

I will show u the entire onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.server_settings, container, false);
    final Button loginButton = (Button) view.findViewById(R.id.addServerSettingsbtn);
    loginButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            //were the magic won't happen.
        }
    });
    return inflater.inflate(R.layout.server_settings, container,false);
}

Upvotes: 0

Views: 74

Answers (2)

J David Smith
J David Smith

Reputation: 4810

Your problem (I believe) is that you're returning an instance of the inflated view that doesn't have the onClick handler assigned.

Try this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.server_settings, container, false);
    final Button loginButton = (Button) view.findViewById(R.id.addServerSettingsbtn);
    loginButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            //were the magic won't happen.
        }
    });
    return view;
}

Upvotes: 5

Blackbelt
Blackbelt

Reputation: 157437

you have to return view instead of inflate again server_setting. inflate returns everytime a new object

Upvotes: 1

Related Questions