Astorian
Astorian

Reputation: 1

Set onclicklistener add text instead of replacing it?

So I have 4 buttons, each button gives a letter. I eventually want this to unlock a password.

But how do I get the letters to be added after each other instead of replacing the previous one?

public class MainActivity extends AppCompatActivity {
TextView txt;
Button btn1, btn2, btn3, btn4;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt=(TextView) findViewById(R.id.mytext);
    btn1=(Button) findViewById(R.id.mybutton);
    btn2=(Button) findViewById(R.id.mybutton2);
    btn3=(Button) findViewById(R.id.mybutton3);
    btn4=(Button) findViewById(R.id.mybutton4);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txt.setText("t");

        }
    });
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txt.setText("i");

Upvotes: 0

Views: 40

Answers (1)

user8341617
user8341617

Reputation: 21

You could simply get the text from before and add the new String to it.

    public void onClick(View v) {
        txt.setText(txt.getText() + "your String here");
    }

Upvotes: 2

Related Questions