Android Toolbar菜单动态切换item的图标

本文讲述了在Android中如何在切换Fragment时动态改变Toolbar的菜单项图标。通过设置Activity的标记状态,监听MenuItem事件,结合onOptionsItemSelected和onPrepareOptionsMenu方法,实现在不同Fragment间 toolbar菜单的动态更新。但这种方法在处理多个Fragment时变得复杂,作者推荐使用新的解决方案,涉及Fragment返回栈和生命周期回调。
摘要由CSDN通过智能技术生成

警示:本文所述的方法过于繁琐,逻辑混乱,代码难以适应复杂情况,并且几乎不可扩展,本文之所以没删是我为了记录自己的踩坑记录,因此如果有人想参照这方面的知识,请参考我的另一篇文章:

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值