How to capture any button through OnClick? [duplicate]

1

I have ten Buttons in my XML and want to change the Text of the button that the user clicks on.

I implemented a View.OnClickListener in my Activity and my onClick looked like this:

@Override
    public void onClick(View view) {
        Button button = (Button) view;
        button.setText("X");
    }

It did not work. Am I required to create a switch for each Button? Is there no way to use a single code for all buttons?

    
asked by anonymous 29.12.2017 / 00:38

3 answers

0

In your XML you can use the onClick attribute so that they all call the click method.

  

XML

<Button
    android:id="@+id/buttonOne"
    ...
    android:onClick="onButtonClick"/>

<Button
    android:id="@+id/buttonTwo"
    ...
    android:onClick="onButtonClick"/>
  

Activity

public void onButtonClick(View view) {
    switch (view.getId()) {

        case R.id.buttonOne: { break; }
        case R.id.buttonTwo: { break; }
        case R.id.buttonThree: { break; }
        ...
    }
}

This way you can save some lines of code. Something else, depending on what functions the buttons on your screen have, you can also use a RecyclerView , which will also save you a lot of code. But this will depend on the function exerted by each button, if they are very different , I believe you to use the same code example, but if they get at the same end , you could use a RecylerView .

For example, if you want to open a screen for each button, you could use RV and depending on the button clicked, return a Bundle to open the corresponding screen, and so on.

    
29.12.2017 / 01:59
0
Look, I was pretty sure this is something you can do. I got that little pulguinha behind the ear, and I decided to test it quickly. The result was that both buttons were left with the text "Clicked!" when clicked.

My XML

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button"
            android:id="@+id/button"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button2"
            android:id="@+id/button2"
            android:layout_below="@+id/button"
            android:layout_alignParentStart="true" />

Na Activity

this.button.setOnClickListener(this)
this.button2.setOnClickListener(this)

 override fun onClick(v: View?) {
    var button = v as Button
    button.text = "Clicked!"
  }
    
29.12.2017 / 12:58
0

Implement View.OnClickListener in your Activity, onClick method do

Remember to set the

Button bt = (Button) findViewById (R.id.button); bt.setOnClickListener (this);

Public void onClick (View view) { Button tmp = (Button) findViewById (view.getId ()); tmp.setText ("Funciona");}
    
01.01.2018 / 03:45