36

I've got the following button in my xml layout file...

<Button
    android:layout_width="150dip"
    android:id="@+id/button1"
    android:layout_height="50dip"
    android:text="@string/login"
    android:layout_marginRight="10dip">
</Button>

I'd like to programmatically add an onclick() listener in it's Java file. How would I do this?

Cavaz
  • 2,996
  • 24
  • 38
Skizit
  • 43,506
  • 91
  • 209
  • 269

6 Answers6

84

You just need something like this:

Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
            //Do stuff here
    }
});
Ross Hambrick
  • 5,880
  • 2
  • 43
  • 34
  • 1
    It'd be nice to know the exception. If it's a NullPointerException, it's because you don't actually have a view with an ID of `button1` in your Activity's layout. If it's a ClassCastException, it's because the view with that ID is not a Button. – Ross Hambrick May 02 '14 at 17:38
  • Yay! Thanks for the reply but I found out that I'm not using the layout where the button is. My bad, thanks again :) – mr5 May 05 '14 at 06:45
  • 1
    @RossHambrick, Is there a way to **add** listener instead of overriding it? – Pacerier Nov 18 '14 at 11:34
  • @Pacerier unfortunately, no. You would have to add that behavior in a Button subclass if you really needed it. – Ross Hambrick Nov 18 '14 at 23:47
22

This answer comes from Five Ways to Wire Up an Event Listener. Please read that blog post for a fuller explanation from the author. See my other answer for these five ways reworked to add multiple onClick listeners.

1. Member Class

public class main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //attach an instance of HandleClick to the Button
        findViewById(R.id.button1).setOnClickListener(new HandleClick());
    }    
    private class HandleClick implements OnClickListener{
        public void onClick(View arg0) {
            Button btn = (Button)arg0;  //cast view to a button
            // get a reference to the TextView
            TextView tv = (TextView) findViewById(R.id.textview1);
            // update the TextView text
            tv.setText("You pressed " + btn.getText());
        }
    }
}

2. Interface Type

public class main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //use the handleClick variable to attach the event listener
        findViewById(R.id.button1).setOnClickListener(handleClick);
    }    
    private OnClickListener handleClick = new OnClickListener(){
        public void onClick(View arg0) {
            Button btn = (Button)arg0;
            TextView tv = (TextView) findViewById(R.id.textview1);
            tv.setText("You pressed " + btn.getText());
        }
    };
}

3. Anonymous Inner Class

public class main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(new OnClickListener(){
            public void onClick(View arg0) {
            Button btn = (Button)arg0;
            TextView tv = (TextView) findViewById(R.id.textview1);
            tv.setText("You pressed " + btn.getText());
            }
        });
    }     
}

4. Implementation in Activity

public class main extends Activity implements OnClickListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(this);
    }    
    public void onClick(View arg0) {
        Button btn = (Button)arg0;
        TextView tv = (TextView) findViewById(R.id.textview1);
        tv.setText("You pressed " + btn.getText());
    }
}

5. Attribute in View Layout for OnClick Events

public class main extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }    
    public void HandleClick(View arg0) {
        Button btn = (Button)arg0;
        TextView tv = (TextView) findViewById(R.id.textview1);
        tv.setText("You pressed " + btn.getText());
    }
}

xml:

<Button android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:onClick="HandleClick"/>
Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
6

You can try this.

public class myNewClass extends Activity implements OnClickListener {
    ................... 
    ...................       

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

        public void onClick(View v) {
                Intent i = new Intent();
                Bundle extras = new Bundle();

        // This will catch the button click 
        // Now do what you wanted to do as a 
        // result of the onClick
        }
 }
apesa
  • 12,163
  • 6
  • 38
  • 43
  • How do I implement `OnClickListener` in my `Activity`? – mr5 Apr 29 '14 at 06:54
  • I edited my answer. Look at the class definition, that is where your implementation for OnClickListener will be declared – apesa Apr 29 '14 at 13:36
1

You can apply onClicklistner in Two way : 1. Under onCreate Method
2. Out side onCreate Method


if we will use under onCreate method then we will use like this:-

protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_graphics1);

        textview1 = (TextView) findViewById(R.id.textview1);
        circleBtn = (Button) findViewById(R.id.circleBtn);

        // Click Listner Under on Create Method
        circleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

}

if You want out side to onCreate Method then first register the onClickListner in onCreate Method like this :-

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_graphics1);

        circleBtn = (Button) findViewById(R.id.circleBtn);

        **// Register on click on button
        circleBtn.setOnClickListener(new ClickMe());**

    }

and then implement clicklistner outside of onCreate Method so full code will be like this :-

public class ActiononBtn extends AppCompatActivity {

    private TextView textview1;
    private Button circleBtn;




    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_graphics1);

        textview1 = (TextView) findViewById(R.id.textview1);
        circleBtn = (Button) findViewById(R.id.circleBtn);

        // Register on click on button
        circleBtn.setOnClickListener(new ClickMe());

    } // Close onCreate Method


    private class ClickMe implements View.OnClickListener {
        public void onClick(View v) {

        }
    }

}//Close main Activity Class
Pradeep Sheoran
  • 493
  • 6
  • 15
0

1.use findViewById(R.id.button1).setOnClickListener(this);

2.and activty implements OnClickListener

actsai
  • 178
  • 1
  • 6
0
<Button
    android:id="@+id/btnOk"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Ok"
    android:layout_marginRight="50dp"
    android:layout_marginLeft="50dp"/>
public class MainActivity extends AppCompatActivity {

    Button btnOk;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnOk = findViewById(R.id.btnOk);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "This button ok click.", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
  • Please, don't post code without an explanation as an answer. Try to explain what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Zsolt Meszaros Feb 03 '21 at 10:47