0

I am trying to make a small app which can give randomly added sentences for me and my friend when we hang out together. I was able to do it by use arrays and random function. The problem is the button only works at the first time I push the button, if I push it again nothing change. I am a newbie to Android and Java so I do not understand much. Here is my code:

 Random r = new Random(); //Khai báo biến random
    n = r.nextInt(14) + 0 ; //hàm tạo biến random

    //Thêm phần tử vào chuỗi
    mangtrochoi[0]=("do A");
    mangtrochoi[1]=("do B");
    mangtrochoi[2]=("do C");
    mangtrochoi[3]=("do D");
    mangtrochoi[4]=("do E");
    mangtrochoi[5]=("do F");
   /* mangtrochoi[6]=("đéo được đánh sd");
    mangtrochoi[7]=("đánh Thảo 10 cái");
    mangtrochoi[8]=("đánh Nhân 10 cái");
    mangtrochoi[9]=("đánh Nguyên 10 cái");
    mangtrochoi[11]=("đánh Bun 10 cái");
    mangtrochoi[12]=("đánh Tiến 10 cái");
    mangtrochoi[13]=("đánh Giang 10 cái");
    mangtrochoi[14]=("đéo được đánh sd");*/

    //Buoc 3: viet code
    BTNrandom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TVhienthi.setText(mangtrochoi[n]);
        }
    });
1
  • check the answers below... Commented Mar 18, 2017 at 9:35

2 Answers 2

1

Move this code inside you Button onclickListener;

 BTNrandom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Random r = new Random(); //Khai báo biến random
            n = r.nextInt(14) + 0 ; //hàm tạo biến random
            TVhienthi.setText(mangtrochoi[n]);
        }
    });

So in each press you will generate a random number which will then set the text.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to set n to a random value inside the click-handler.

BTNrandom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            n = r.nextInt(14) + 0 ;
            TVhienthi.setText(mangtrochoi[n]);
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.