我有3个活动,它们都有一个工具栏,它们都工作正常,但它们的工具栏都有细微差别,所以我不得不在每个活动中写出很多相似的行,是否可以上课对于工具栏自定义xml布局与php相同,在php中当你创建一个与你编写标题的所有页面共享的标题时,它会根据你所在的页面动态更改,请注意代码工作正常如果他们是分开的我唯一的问题是我想让我的工具栏方法与我的活动方法分开。
您可以创建自己的工具栏,从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
在活动类中,替换您的默认工具栏
关于工具栏,继承,包括等的自定义,你可以做很多事情。一种方法是从qazxsw poi继承。将自定义工具栏放到相应的活动any_name.xml中。
3个活动中的每个活动都将从您的UpperActivity继承,并且可以覆盖特别是为自己目的合法的自定义设置。
您可以简单地创建一个基本活动,您可以在其中定义工具栏修饰的方法。可以使用该方法编写工具栏的所有类似代码行。如果您希望该方法对每个活动执行不同的装饰,则可以采用方法参数形式进行的所有更改。这将帮助您减少在每个活动中编写的重复代码行。
例:
android.support.v7.widget.Toolbar
因此,这将是Base Activity类,它将从您的其余活动扩展而不是直接扩展AppCompatActivity。
现在为您创建的每个新活动扩展CustomBaseAcitivity类。这也可以用于您的活动中发生的其他重复代码,通过使用继承,您可以重用编写的代码。不是为每个活动反复编写相同的代码,而是可以在BaseActivity中编写它,它将充当其他所有活动的父类。
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
}
}