I made an abstract base activity called MyBaseActivity that extends Activity. I then extend MyBaseActivity for all of my concrete sub-activities. I did that so that I wouldn't have to set up the same menu for every single sub-activity.

However, I still have the following code repeated in all of my activities' onCreate() calls.

// Custom View for ActionBar
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
View view = View.inflate(getApplicationContext(), R.layout.actionbar_top, null);
actionBar.setCustomView(view);

Is there a way to avoid repeating this code? Can I put it in MyBaseActivity? If so, do I need to send it the context? How would I do that?

有帮助吗?

解决方案

Put it in your base Activity's onCreate().

In the subclass, when you call super.onCreate() the code will be executed.

public class BaseActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // Custom View for ActionBar
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        View view = View.inflate(getApplicationContext(), R.layout.actionbar_top, null);
        actionBar.setCustomView(view);
    }

}


public class SubActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState); // this calls BaseActivity's onCreate()

       // at this point your actionbar custom view will have been set up

    }

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top