Skip to content
Advertisement

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:

@Override
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(R.id.button3);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        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();
            dialog.show();
        }
    });


    return i;
}

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

Answer

ok I have fixed this by using FragmentManager

like :-

FragmentManager fragment = getSupportFragmentManager();
fragment.beginTransaction().replace(R.id.fragmentContainerView, fragment_id_upload.class,null).commit();


R.id.fragmentContainerView  //this is fragment container view

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

Advertisement