Skip to content

Java OnClickListener not working in Android Fragment

I am trying to add a simple click on a button in a Fragment but the event is ignored.

This is the code:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View i =  inflater.inflate(R.layout.fragment_id_upload, container, false);

    btn = i.findViewById(;

    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Log.i("data","ok clickled");
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("hjgdfhfghfghf gfdgf");
            AlertDialog dialog = builder.create();

    return i;

I don’t know what is wrong in the code?


ok I have fixed this by using FragmentManager

like :-

FragmentManager fragment = getSupportFragmentManager();
fragment.beginTransaction().replace(, fragment_id_upload.class,null).commit();  //this is fragment container view

for more details:- go to Android Studio – Fragment onClickListener not working