Extending class for activity

为君一笑 提交于 2019-12-20 14:13:04

问题


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!!


回答1:


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.




回答2:


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.
}


来源:https://stackoverflow.com/questions/8255614/extending-class-for-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!