Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending class for activity

I'm totally new to Android (Java) Development and I'm so excited about it! The developers guide of Google is fantastic and I learned a lot in a small time. It even keeps me awake during the night ;)

Today I went through making menu's and there's something that I can't understand. It's about extending classes. The guide says:

Tip: If your application contains multiple activities and some of them provide the same Options Menu, consider creating an activity that implements nothing except the onCreateOptionsMenu() and onOptionsItemSelected() methods. Then extend this class for each activity that should share the same Options Menu. This way, you have to manage only one set of code for handling menu actions and each descendant class inherits the menu behaviors.

The point I don't get is how to extend a class... Let say I have a MainActivity and a SubActivity. I want to have the same menu in both activities so I make a MainMenuActivity. How do I extend this class for both activity's?

Yes I do searched on the net but couldn't find any usable. I really want to understand it so I hope anyone can help me out with some samplecode + explanation. Thank you in advance!!

like image 727
MartijnG Avatar asked Nov 24 '11 10:11

MartijnG


2 Answers

It's quite simple really.

MainMenuActivity

public class MainMenuActivity extends Activity {
   //Override or add whatever functionality you want other classes to inherit.
}

MainActivity

public class MainActivity extends MainMenuActivity {
   //Add what is specific to MainActivity. The menu will be inherited from MainMenuActivity.
}

SubActivity

public class SubActivity extends MainMenuActivity {
   //Add what is specific to SubActivity. The menu will be inherited from MainMenuActivity.
}
like image 101
kaspermoerch Avatar answered Oct 21 '22 03:10

kaspermoerch


What they mean is the following:

Normally you would have:

public class MyActivity extends Activity{...}

If you have 4-5-6... of those activities, and each of them uses the same menu code, you could just copy and paste the code 4-5-6.. times. Or you could do this:

public class BaseActivity extends Activity{

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //My menu code  
    }
}

And use this class for your 4-5-6... Activities:

public class MyActivity extends BaseActivity{...}

This way you don't need to copy your menu creation code into all your Activities, and moreover, you don't have to edit 4-5-6... classes to edit a small bit of creation of the menu. The menu code is now also in MyActivity.


You could also have a look here, it explains what extends means.

like image 44
nhaarman Avatar answered Oct 21 '22 03:10

nhaarman