警示:本文所述的方法过于繁琐,逻辑混乱,代码难以适应复杂情况,并且几乎不可扩展,本文之所以没删是我为了记录自己的踩坑记录,因此如果有人想参照这方面的知识,请参考我的另一篇文章:
Toolbar菜单动态改变item的图标(二)
大家都知道,Fragment的启动速度比Activity快很多,因此在开发中如果每一个界面都使用一个Activity显然不那么好,这时候我们一般用Activity来充当管理的角色,界面的内容都放在Fragment中。可是由于每个Fragment都对应一个功能界面,因此每个Fragment的顶部工具栏都应该是不同的,但是ActionBar或者ToolBar都是属于Activity的,这时候我们就需要在切换Fragment的时候使Toolbar也做出相应的动态切换。
我们来举一个简单的例子,打开个人信息Activity(MyInformationActivity),布局文件如下。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".myinformation.MyInformationActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/my_information_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="@style/WhiteToolBar">
</android.support.v7.widget.Toolbar>
<FrameLayout
android:id="@+id/alter_my_information_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/my_information"
android:name="com.icon.app.myinformation.MyInformationFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
布局很简单,里面只放置了一个Toolbar和第一个Fragment (MyInformationFragment),因此,只要这个Activity一启动,首先展示在用户眼前并和用户交互的就是MyInformationFragment,MyInforamtionFragment的布局文件我就不放了,直接放效果图,如下:
展示的用户信息除了头像以外,主要就是姓名,性别,友好度这三项。大家可以注意到 ,toolbar的标题是“我的信息”,右上角的MenuItem是一支笔的图片。我们要实现的是点击右上角的menuitem,创建第二个Fragment (AlterMyInformationFragment) 使其到达Activity的最顶端,覆盖当前的MyInforamtionFragment。于是,我们在onOptionsItemSelected(MenuItem item)方法中进行监听,当用户点击右上角的笔图标时,启动新的Fragment,MyInformationActivity的代码如下:
public class MyInformationActivity extends AppCompatActivity {
private Toolbar toolbar;
private AlterMyInformationFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
s