Reputation: 172
here is my code:
public class MainActivity extends Activity implements View.OnClickListener {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
Toast.makeText(getApplicationContext(), "onClick method was called", Toast.LENGTH_LONG).show();
break;
}
}
}
For some reason nothing happens and no toast shows up. Did I miss anything ? Thanks
Upvotes: 0
Views: 1524
Reputation: 10704
As an alternative of Vipul answer you can also add the attribute onClick
in the Button
tag in the XML layout file.
Example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="myMethod" />
</RelativeLayout>
And, in your MainActivity.java, remove the View.OnClickListener
implemented interface (thanks @donfuxx) add the following method:
public void myMethod(View v) {
//do something
}
Upvotes: 5
Reputation: 17401
write:
b.setOnClickListener(this);
in onCreate
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
}
you must set a listener to the button for onClick
to work
Upvotes: 10