How to create a button in a Fragment for android?

Asked

Viewed 20 times

1

I created a button that aims to Random an image. However, the button and image are not appearing on android. The code I’m using is as follows::

 ImageView imageView;
Random r;
Integer[] images = {
        R.drawable.img_fra,
        R.drawable.img_acai,
};

int pickedImage = 0, lastPicked = 0;

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

        // Inflate the layout for this fragment
        View view = inflater.inflate(fragment_home, container, false);
        view.findViewById(R.id.imagedizqqcoisa);
        view.findViewById(R.id.buttondizqqcoisa);

        r = new Random();

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                do {
                    pickedImage = r.nextInt(images.length);
                } while (pickedImage == lastPicked);

                lastPicked = pickedImage;
                imageView.setImageResource(images[r.nextInt(images.length)]);


                pickedImage = r.nextInt(images.length);
            }
        });
        return view;

    }

}
  • Where are the buttons? You declared the buttons? It should be so Button button = view.findViewById(R.id.buttondizqqcoisa);. And so button.setOnClickListener(new View.OnClickListener()

  • Yes I declared the buttons. I did as I said and it’s still not working.

  • I already have the image and the button but the button does not work. The code is at the beginning.

  • Note that your onClick() method is not in the boot but in the frgament view. In this part view.setOnClickListener(new View.OnClickListener()

  • @Bernardolopes already got it. Thank you

No answers

Browser other questions tagged

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