Several activities using same listener
I got 4 activites that all 开发者_Python百科include a xml-footer which contains 4 buttons (one for each activity). I would now like to setup onclicklisteners to these buttons (it's a self made menu in the footer).
The question is, how do I use listeners so that I can reuse code? I have two ideas:
Create a class that implements onclicklistener and in every activity i would get the buttons and then create a new instance of the listener class and do button.setOnClickListener(onClickListener) The problem is that in the listener class, how would i check which button called the event? And how would I create an intent to start an activity, usually i would do: Intent intent = new Intent(FromActivity.this, ToAcitivty.class) But i don't have the reference to FromActivity.
Create a base class that extends from activity and then the 4 activies will extend from the base class. I would then like to setup the listeners in the base class. The problem here is that i can't get the references to the buttons by doing Button button1 = (Button)findViewById(R.id.menu_button1); button1 will be null. I haven't even called setEventView because this should be done in the activity not in the base class.
Any ideas?
Thank you
Same code is here:
public class MyClass extends Activity implements View.OnClickListener{
btnA=(Button)findViewById(R.id.btnA);
btnA.setOnClickListener(this);
btnB=(Button)findViewById(R.id.btnB);
btnB.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
Button clickedButton = (Button) v;
switch (clickedButton.getId())
{
case R.id.btnA:
Intent regIntent = new Intent(Home.this,Registration.class);
startActivityIfNeeded(regIntent, 1);
break;
case R.id.btnB:
//Some code
break;
}
}
(edited as the original first line is broken on code format.
精彩评论