So I have these five buttons that I want to be always present in all activities, sort of shortcut buttons to other activities. So i created a separate xml layout for this and just included them in the other activity layouts. I also created a class with corresponding methods that will handle the button clicks.
Now my problem is that I don’t know how to use/declare this class in my activities. When I try to run my app, logcat gives me an error that it couldn’t find the method handling the click.
How can I do that?
Here’s my buttons handler class:
package com.meralco.pms;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Toast;
public class ButtonsHandler extends Activity{
protected void startSin() {
Intent launch = new Intent(this, SinActivity.class);
startActivity(launch);
}
protected void startCity() {
Intent launch = new Intent(this, CityActivity.class);
startActivity(launch);
}
protected void startHelp() {
Intent launch = new Intent(this, HelpActivity.class);
startActivity(launch);
}
protected void startAll() {
Intent launch = new Intent(this, AllActivity.class);
startActivity(launch);
}
protected void startDate() {
Intent launch = new Intent(this, DateActivity.class);
startActivity(launch);
}
public void buttonClick(View v) {
switch(v.getId())
{
case R.id.button_sin:
Toast.makeText(v.getContext(), "SIN" , Toast.LENGTH_SHORT).show();
startSin();
break;
case R.id.button_city:
startCity();
Toast.makeText(v.getContext(), "CITY" , Toast.LENGTH_SHORT).show();
break;
case R.id.button_date:
startDate();
Toast.makeText(v.getContext(), "DATE" , Toast.LENGTH_SHORT).show();
break;
case R.id.button_all:
startAll();
Toast.makeText(v.getContext(), "ALL" , Toast.LENGTH_SHORT).show();
break;
case R.id.button_help:
startHelp();
Toast.makeText(v.getContext(), "HELP" , Toast.LENGTH_SHORT).show();
break;
}
}
}
I think I am missing constructors. Am I heading the right way or I got it totally wrong? TIA!
I would change your ButtonsHandler to extend
Fragmentinstead of Activity. Then you can include this fragment in all the rest of your activities. They will have to extendFragmentActivityin order to host your ButtonsHandler fragment and the layout files will referencecom.meralco.pms.ButtonsHandleras a fragment.In order to support fragments in Android versions before 3.0, you’ll want to use the Android Compatibility Library: http://developer.android.com/sdk/compatibility-library.html
You’ll also want to read up about Fragments: http://developer.android.com/guide/topics/fundamentals/fragments.html
They are the recommended way for Android applications to re-use UI components like in this case:
With regards to your buttons, you’ll want to hook up listeners like so: