简体   繁体   English

android:自己的类扩展活动和/或listactivity

[英]android: own class extending activity and/or listactivity

I have a couple of things which are the same in all my Activities throughout my application, eg an optionsmenu and some code which needs to run onresume, onrestart and onpause. 我在整个应用程序的所有活动中都有几处相同的内容,例如,一个选项菜单和一些需要在onresume,onrestart和onpause上运行的代码。 I figured it would be a smart approach to put them in my a class MyListActivity extends ListActivity and then have all my activities extending MyListActivity. 我认为将它们放入类MyListActivity扩展ListActivity,然后让我的所有活动扩展MyListActivity是一种明智的方法。

This worked out just fine until I created an activity which didn't have a ListView. 在我创建一个没有ListView的活动之前,这工作得很好。 the App crashes because ListActivity expects a ListView. 该应用程序崩溃,因为ListActivity需要一个ListView。 However, this new activity does not need a ListView, but would still need all my functions / Overrides in MyListActivity . 但是,此新活动不需要ListView,但仍然需要我的所有函数/ MyListActivity中的Overrides。

Right now I can think of two solutions. 现在,我可以想到两种解决方案。 One: add a dummy listview to the layout with visibility = false, height & width = 0 (haven't tried this, but i guess it should work). 一种:将虚拟列表视图添加到可见性= false,高度和宽度= 0的布局中(还没有尝试过,但是我想它应该可以工作)。 And Two: copy/paste the contents of the MyListActivity class into a MyActivity extends Activity class. 还有两个:将MyListActivity类的内容复制/粘贴到MyActivity扩展Activity类中。 I feel very silly doing this, but I don't have any other ideas on how to solve this issue. 我这样做很愚蠢,但是对于如何解决这个问题我没有其他想法。

Any ideas on how to handle this nicer? 关于如何处理更好的任何想法?

Thanks 谢谢

I think you can implement all the features in an Activity subclass (eg, MyActivity ) and make the MyListActivity class a subclass of the MyActivity class. 我想你可以实现在所有的功能Activity的子类(如MyActivity ),使MyListActivity类的子类MyActivity类。

Other approach is to make a helper class which contains all the features in static methods with an Activity object as the first argument. 另一种方法是制作一个包含静态方法中所有功能的帮助程序类,并将Activity对象作为第一个参数。 In this case you don't need to create MyActivity or MyListActivity classes, but you need to call methods of the helper class in every Activity subclass you want to inherit these features. 在这种情况下,您不需要创建MyActivityMyListActivity类,但是需要在要继承这些功能的每个Activity子类中调用helper类的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM