I have 7 buttons in all my 6 activities. All 6 buttons have the same functionality in all activities. How can I perform a common click event lisnter for these 6 buttons.
Putting more words in Sagar's answer given above.
As you have said you have 7 buttons in your 6 activities, I assume all the 7 buttons have same functionality/code.
Step 1: Include android:click="btnFirstClick"
in <Button>
inside your XML layouts.
Step 2: Define abstract BaseActivity class by extending Activity and include methods with the same name you have given in android:onClick
attribute.
abstract public class BaseActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void btnFirstClick(View v) {
}
public void btnSecondClick(View v) {
}
.....
.....
// same for other buttons
}
Step 3: Now extends this BaseActivity to all your 6 activities.
For example:
public class FirstActivity extends BaseActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_first);
}
}
You can create a new class that implements View.OnClickListener like this:
public class MyClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
// TODO handle the click
}
}
In all your activities you can then set the click listener like this:
button.setOnClickListener(new MyClickListener());
You could even save the context in the class for displaying Toasts etc.
public class MyClickListener implements View.OnClickListener {
private Context context;
public MyClickListener(Context context) {
this.context = context;
}
@Override
public void onClick(View view) {
Button button = (Button) view;
Toast.makeText(this.context, button.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With