How to add Onclick to a fragment?

2

I'm trying to add onclick to my fragment, but I'm not getting it, where is it wrong?

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

    return inflater.inflate(R.layout.fragment_more, container, false);

    Button button = (Button) view.findViewById(R.id.btn_conferma);
    button.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // do something
            } 
        }); 
    return view;
    }
    
asked by anonymous 11.12.2018 / 23:31

1 answer

1

The problem is that you are returning the View before setting up the Button and its listener. In this line:

return inflater.inflate(R.layout.fragment_more, container, false);

The right thing to do is:

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

Button button = (Button) view.findViewById(R.id.btn_conferma);
button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // do something
        } 
    }); 
return view;
    
11.12.2018 / 23:53