How to pick up the text from a button?

Asked

Viewed 1,344 times

0

So, I have a question and answer game. Each question has 4 answers (placed on button labels). How do I get the text from the button clicked to compare to a String?

1 answer

4


You must first search for the XML element,

 final Button btnResposta1 = (Button) findViewById(R.id.btnResposta1);
 final Button btnResposta2 = (Button) findViewById(R.id.btnResposta2);

then implement onClickListener

private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //faca um cast para Button
            Button botao = (Button)view;
            //pegue o texto
            String respostaBotao = botao .getText().toString();
            switch (view.getId()){
                case (R.id.btnResposta1):
                    //codigo caso clicar resposta 1
                    break;
                case (R.id.btnResposta2):
                    //codigo caso clicar resposta 2
                    break;
        }
}

then associate to the button reader.

btnResposta1.setOnClickListener(onClickListener);
btnResposta2.setOnClickListener(onClickListener);

hope I’ve helped!

Browser other questions tagged

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