TabHost: What if I need to handle onOptionsItemSelected each in separate Tab/Activity
I need to have a TabHost
consisting of two tabs
where each tab
represented by a separate Activity
. Each Activity
has its own data fields and methods to operate on them. I want each tab
to have its own menu
and for this menu
I need onOptionsItemSelected()
method to be a part of the class
to make it able to invoke methods of this class
.
What the best approach would it be to implement this?
I've started with menu
definition in the class which represents TabHos开发者_如何学运维t
, but then faced with a problem I don't have an access to methods of my Activities
. I decided to make methods of Activities
static
to have access to them but finally I would need to define almost all fields of these Activities
as static which doesn't seem to be a good solution for me.
Update:
It became much easier then I thought. In onOptionsItemSelected() you can get the current Activity
of your opened tab
.
SecondActivity sa = (SecondActivity)this.getCurrentActivity()
sa.myPublicMethod();
This really depends on what sort of functionality you are implementing. You could have each activity implement an interface with the instance methods you need and then have the tabhost contain a reference to the current activity of type interface. If you do this, make sure to update the reference each time you switch to another activity.
Use onOptionItemSelected()
in each Activity
and then call a static method, passing in the Activity
you are calling from. You could then check the class
of the Activity
and then cast Activity
to TabOneActivity
or TabTwoActvity
. If the methods you need are public (or friendly, if in the same package) you will have access without the need for them to be static.
Edit:
Create a class like so with the static method to be called from each onOptionItemSelected()
.
class GlobalStaticMethods {
// Pass in the following as a which (avoids having to check class using SimpleClassName)
public static final int TabActivityOne = 1;
public static final int TabActivityTwo = 2;
public static myOnOptionItemSelected(final Activity activity, final int which) {
switch (which) {
case TabActivityOne:
((TabActivityOne)activity).tabActivityOneMethod();
break;
case TabActivityTwo:
((TabActivityTwo)activity).tabActivityTwoMethod();
break;
}
}
}
精彩评论