安卓:分享活动之间code的最好方法?方法、code

2023-09-07 14:58:18 作者:心有不甘

我用在包含一个工具栏和搜索文本框和按钮的几个活动包括。我不想要复制所有相同的code到每个,因为这变成了一场噩梦的修改和变化,等等。

I'm using an include in several activities that contain a toolbar and a search text box and button. I don't want to copy all of the same code to each, because that becomes a nightmare for edits and changes, etc.

什么是最好的方式来完成这件事?

What is the best way to get this done?

我最初的想法是创建一个新的类,把按钮code。在那里,该活动传递给它,但我只是不知道如何做到这一点。

My initial thought is to create a new class, put the button code in there, and pass the activity to it, but I'm just not sure how to do this.

在此先感谢您的帮助! 马克

Thanks in advance for your help! Mark

推荐答案

创建一个 BaseActivity 与包括布局布局在该功能的 BaseActivity 。然后扩展BaseActivity 在其他活动

Create a BaseActivity with the included layout for its layout with the functionality in that BaseActivity. Then extends BaseActivity in your other Activities.

这样做,你可以重写的功能在您的任何活动如果你需要从他们身上更多的/不同的功能。我这样做,这样我就可以有一个完全定制操作栏在我所有的活动。我的背扣,溢出按钮,另一个图像按钮功能都包含在 BaseActivity

Doing this you can override the functions in any of your Activities if you need more/different functionality from them. I do this so I can have a completely custom "Action Bar" in all of my Activities. My back button, overflow button, and another image button functionality is all contained in the BaseActivity.