有没有更好的方法来编写android工具栏重复方法,而不是在每个活动中编写相同的代码
我有3个活动,它们都有一个工具栏,它们都工作得很好,但它们的工具栏都有一点不同,所以我必须在每个活动中编写很多类似的行,是否可以为工具栏定制一个与php相同的xml布局类,在php中,当您创建一个与所有页面共享的标题时,您可以根据所处的页面动态更改标题,请注意,如果将工具栏方法与活动方法分开,则代码可以正常工作。唯一的问题是,我希望将工具栏方法与活动方法分开。您可以在工具栏自定义、继承、包含等方面做很多事情。一种方法是从有没有更好的方法来编写android工具栏重复方法,而不是在每个活动中编写相同的代码,android,android-studio,android-toolbar,Android,Android Studio,Android Toolbar,我有3个活动,它们都有一个工具栏,它们都工作得很好,但它们的工具栏都有一点不同,所以我必须在每个活动中编写很多类似的行,是否可以为工具栏定制一个与php相同的xml布局类,在php中,当您创建一个与所有页面共享的标题时,您可以根据所处的页面动态更改标题,请注意,如果将工具栏方法与活动方法分开,则代码可以正常工作。唯一的问题是,我希望将工具栏方法与活动方法分开。您可以在工具栏自定义、继承、包含等方面做很多事情。一种方法是从android.support.v7.widget.toolbar继承。将C
android.support.v7.widget.toolbar
继承。将CustomToolbar放到相应的activity\u any\u name.xml中
这3个活动中的每一个都将从您的UpperActivity继承,并且可以覆盖仅用于自身目的的自定义设置。您只需创建一个基本活动,在其中可以定义工具栏装饰的方法。工具栏的所有类似代码行都可以用该方法编写。如果希望该方法对每个活动执行不同的修饰,那么可以采用方法参数形式进行所有更改。这将帮助您减少在每个活动中编写的重复代码行 例如:
class CustomBaseActivityClass extends AppCompatActivity{
// Overriden methods
// onCreate()
// onStart()
public void decorateToolbar(Toolbar toobar //pass the toolbar reference to be attached,
// optional: you can take required information from the extending activity to perform different actions for toolbar){
// write the repetitive code for defining and attaching toolbar
}
}
因此,这将是从活动的其余部分扩展而来的基本活动类,而不是直接扩展AppCompatActivity
现在,为您创建的每个新活动扩展CustomBaseActivity类。
这也可以用于活动中发生的其他重复代码,通过使用继承,您可以重用编写的代码。
您可以在BaseActivity中编写代码,而不是为每个活动反复编写相同的代码,该BaseActivity将充当每个其他活动的父类
SampleActivity extends CustomBaseActivity{
void onCreate(// same overridden method){
decorateToolbar(); // calling decorate toolbar method for attaching toolbar to the current activity.
}
}
您可以创建自己的工具栏,该工具栏从android.support.v7.widget.toolbar扩展而来。 那样
public class YourToolbar extends android.support.v7.widget.Toolbar{
public YourToolbar (Context context) {
super(context);
initViewComponents(context);
}
public YourToolbar (Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initViewComponents(context);
}
public YourToolbar (Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initViewComponents(context);
}
private void initViewComponents(Context context) {
//here the shared code between all activities
if(context instanceof FirstActivity){
//code fore just the first Acitivity
}if(context instanceof SecondActivity){
//code fore just the secondAcitivity
}else if(context instanceof ThreardActivity){
}
//here the shared code between all activities
}
}
在xml视图中,将默认的tolbar替换为您的tolbar
在Activities类中,用您的替换默认工具栏我面临一个问题,在initviewComp中,当我尝试实例化工具栏时,它在setSupportActionBar(工具栏)上给出了一个无法解决的错误方法;getSupportActionBar().setDisplayHomeAsUpEnabled(true);你能和我分享一下你的这部分代码吗?当你使用操作栏的方法时,它似乎变得疯狂了。我把它移除,用充气打开弹出菜单,它工作得很好;必须从活动中调用,或者您可以将上下文解析为活动并调用setSupportActionBar(工具栏);