简体   繁体   中英

OnClickListener doesn't work in a fragment

I have here a problem with the onClicklistener method in a fragment. If I click on the button nothing happens and I don't know why. No error and no output. I've tried to implements the OnClickListener or set a (Button) before the view.findViewById(R.id.button); but nothing helps. I've seen much questions here in Stack Overflow about this problem but no solution from there helps me:/

Do you have any ideas? Thank You!

package com.christoph.myapplication.ui.home;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.christoph.myapplication.R;

public class HomeFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_home, container, false);

        final Button button= view.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button.setBackgroundColor(Color.RED);
                System.out.println("Hallo");
            }
        });
        return view;
    }
}

You can add click listener rather in onViewCreated function. Try it and let me know if it works. Check android fragment lifecycles documentation for more info.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM