Bhushan Babar Bhushan Babar - 1 year ago 124
Android Question

onclick event in fragment activity not working

I have a activity A in which I have a fragment.

In this activity Fragment changes to fragment A(default when activity A is called) or fragment B based on user input in activity A.

In both fragments A & B I have a button with on click listener. but this button works only for the first time when activity A is started.

when user changes fragment the button in those fragments stop responding to on click.

Please suggest what I need to do in order to make buttons in fragment A & B work when fragments are changed by user.

I am replacing fragments based on user input by this code:

fr = new FragmentOneDice();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(, fr);

In fragment activity code is like this for on click listener button.

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.Collections;

public class FragmentOneDice extends Fragment implements View.OnClickListener {

Button button1;
View view;

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

//Inflate the layout for this fragment

view = inflater.inflate(R.layout.activity_fragment_one, container, false);

button1 = (Button) view.findViewById(;

return view;


public void onClick(View v) {

Answer Source

The problem was in my activity_main.XML, where I had defined <Fragment> as a placeholder for all fragments and had set one fragment as default. So when other fragment was loaded it was getting overlapped resulting in on click event on the button not working, I changed the <Fragment> to <FrameLayout> as a placeholder. And my problem was solved.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download