How to add Onclick in a Fragment?

Asked

Viewed 700 times

2

I’m trying to add onclick in my Ragment, but I’m not getting it, where it’s 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;
    }

1 answer

1


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

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

The right thing 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;
  • Hello friend, thank you very much, working!

  • Tranquilo @Danielpereira

Browser other questions tagged

You are not signed in. Login or sign up in order to post.