Problem making method that checks which button was clicked

2

I am creating a screen with 3 buttons in which each button to click will need to be redirected to a different site. I implemented this code, there is no error, I can even click on the button, so when the page is loaded there is an error in the application and it closes itself. What am I doing wrong in this method?

    
asked by anonymous 27.05.2016 / 05:56

1 answer

5

This code you posted does not have a click function, it is running all this when OnCreateView() starts. Try to do this:

In your class, right after extends Cronograma , add implements View.OnClickListener .

And in OnCreateView() do this:

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

    View view = inflater.inflate(R.layout.solicitacoes, container, false);
    Button button1 = view.findViewById(R.id.id_do_button1);
    Button button2 = view.findViewById(R.id.id_do_button2);
    Button button3 = view.findViewById(R.id.id_do_button3);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
    button3.setOnClickListener(this);

  return view;
 }

Then to finish, just create (the correct term I think is to implement) the function of OnClick : Note: I gave a simplified function using switch instead of if , taking into account that you only want to get the click event of the buttons in this classe :

@Override
public void onClick(View v) {
   String url = "";
   switch (v.getId()) {
     case R.id.button:
       url = "sua url aqui";
       break;
     case R.id.button:
       url = "sua url aqui";
       break;
     default: // padrão, seria igual o else aqui
       url = "url padrão aqui";
       break;

     Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url))...
     startActivity(it);
   }
}
    
27.05.2016 / 16:00