设置所有活动的工具栏 [英] Set toolbar for all Activities
问题描述
在我的应用中,我想为除mainActivity之外的所有活动创建一个唯一的工具栏. 我已经为设置标题和徽标编写了此代码,但是在工具栏中,我也记录了用户名. 因此,我在仪表板活动中编写了以下代码:
In my app I would like to make a unique toolbar for all activities except for mainActivity. I have written this code for set Title and logo, but in toolbar I also have username logged. So I have written in my dashboard activity this code:
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
assert myToolbar != null;
myToolbar.setLogo(R.mipmap.logo_big);
TextView usernameField = (TextView) findViewById(R.id.username);
try {
usernameField.setText(User.getInstance().getUsername());
} catch (JSONException e) {
e.printStackTrace();
}
我做了一个可以包含在所有xml文件中的布局. 但是,如何在所有活动中重用此代码而不进行复制和粘贴?
And I made a layout that can be included in all xml files. But How can I reuse this code in all my activities without copy and paste?
单身做错了吗?或实用程序类?
Is it wrong to make a singleton? or a utility class?
谢谢
推荐答案
您可以创建一个基本活动,该活动运行通用代码并使所有其他活动都继承自该通用代码:
You could create a base activity that runs the common code and have all other activities inherit from it:
// the base class
public abstract class BaseActivity extends AppCompatActivity
{
protected final void onCreate(Bundle savedInstanceState, int layoutId)
{
super.onCreate(savedInstanceState);
setContentView(layoutId);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
assert myToolbar != null;
myToolbar.setLogo(R.mipmap.logo_big);
TextView usernameField = (TextView) findViewById(R.id.username);
try {
usernameField.setText(User.getInstance().getUsername());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
// inheriting activity
public class SomeActivity extends BaseActivity
{
protected final void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState, R.layout.some_layout);
}
}
这篇关于设置所有活动的工具栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!