在Fragment中如何使用Toolbar

本文介绍了一个使用Toolbar、Fragment、ViewPager及RadioButton实现类似微信主界面的应用案例。文章详细展示了如何通过这些组件来创建导航栏,并提供了关键代码片段。此外,文中还提到了在NoActionBar主题下使用Toolbar时的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个Toolbar实在折磨了我好几天。。。知道看到下面这个提醒然后出去吹了吹风,终于弄出来了....其实跟提醒无关。我卡在这句上了....

        toolbar.inflateMenu(R.menu.menu_main);
代码中还包含 fragment+viewpager+radiobutton实现的仿微信主界面效果。


还是要提醒:
在NoActionBar的主题中
1. onCreateOptionsMenu方法不会运行
2. 即使在关联ActionBar后也不会触发onCreateOptionsMenu,此监听只对ActionBar有效

FragmentStore.java

package com.example.demo.myapplication.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.example.demo.myapplication.R;
import com.example.demo.myapplication.activity.SelectActivity;
import com.example.demo.myapplication.activity.UpdatePhotoActivity;

public class FragmentStore extends Fragment {

    Activity mActivity;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mActivity = getActivity();

        //fragment的布局文件
        View view = inflater.inflate(R.layout.fragment_special_offer, container, false);
       
        TextView content = (TextView) view.findViewById(R.id.content);
        content.setText("商城");

        Toolbar toolbar = (Toolbar)view.findViewById(R.id.toolbar);

<pre name="code" class="java">        ImageButton selectBtn= (ImageButton) view.findViewById(R.id.select);
        selectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mActivity,"你点击了选择按钮",Toast.LENGTH_SHORT).show();
            }
        });
//导入fragment的menu文件 toolbar.inflateMenu(R.menu.menu_main); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mActivity.finish(); case R.id.overflow: Intent intent=new Intent(); intent.setClass(mActivity, SelectActivity.class); startActivity(intent); //设置切换动画,从右边进入,左边停留 mActivity.overridePendingTransition(R.anim.in_from_right, R.anim.stay); } return true; } }); return view; }}


MainActivity.java 

package com.example.demo.myapplication.activity;


import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.os.Bundle;


import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.demo.myapplication.R;

import com.example.demo.myapplication.adapter.MyFragmentPagerAdapter;
import com.example.demo.myapplication.fragment.FragmentMine;
import com.example.demo.myapplication.fragment.FragmentSpecialOffer;
import com.example.demo.myapplication.fragment.FragmentStore;
import com.example.demo.myapplication.fragment.MyFragment3;

import java.util.ArrayList;
import java.util.List;

public class MainActivity  extends BaseActivity implements RadioGroup.OnCheckedChangeListener,
        ViewPager.OnPageChangeListener {

    //UI Objects
    private RadioGroup  rg_tab_bar;
    private RadioButton rb_channel;
    private RadioButton rb_message;
    private RadioButton rb_better;
    private RadioButton rb_setting;
    private ViewPager vpager;

    //几个代表页面的常量
    public static final int PAGE_ONE = 0;
    public static final int PAGE_TWO = 1;
    public static final int PAGE_THREE = 2;
    public static final int PAGE_FOUR = 3;

    private MyFragmentPagerAdapter mAdapter;
    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);

        bindViews();
        rb_channel.setChecked(true);
    }


    private void bindViews() {
        rg_tab_bar = (RadioGroup) findViewById(R.id.rg_tab_bar);
        rb_channel = (RadioButton) findViewById(R.id.rb_channel);
        rb_message = (RadioButton) findViewById(R.id.rb_message);
        rb_better = (RadioButton) findViewById(R.id.rb_better);
        rb_setting = (RadioButton) findViewById(R.id.rb_setting);
        rg_tab_bar.setOnCheckedChangeListener(this);

        //构造适配器
        List<Fragment> fragments=new ArrayList<Fragment>();
        fragments.add(new FragmentSpecialOffer());
        fragments.add(new FragmentStore());
        fragments.add(new MyFragment3());
        fragments.add(new FragmentMine());
        mAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),fragments);
        //设定适配器
        vpager = (ViewPager) findViewById(R.id.vpager);
        vpager.setAdapter(mAdapter);
        vpager.setCurrentItem(0);
        vpager.addOnPageChangeListener(this);
    }
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_channel:
                vpager.setCurrentItem(PAGE_ONE);
                break;
            case R.id.rb_message:
                vpager.setCurrentItem(PAGE_TWO);
                break;
            case R.id.rb_better:
                vpager.setCurrentItem(PAGE_THREE);
                break;
            case R.id.rb_setting:
                vpager.setCurrentItem(PAGE_FOUR);
                break;
        }
    }
    //重写ViewPager页面切换的处理方法
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        //state的状态有三个,0表示什么都没做,1正在滑动,2滑动完毕
        if (state == 2) {
            switch (vpager.getCurrentItem()) {
                case PAGE_ONE:
                    rb_channel.setChecked(true);
                    break;
                case PAGE_TWO:
                    rb_message.setChecked(true);
                    break;
                case PAGE_THREE:
                    rb_better.setChecked(true);
                    break;
                case PAGE_FOUR:
                    rb_setting.setChecked(true);
                    break;
            }
        }
    }

}

MyFragmentPagerAdapter.java
package com.example.demo.myapplication.adapter;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;

import java.util.List;

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> mFragments;


    public MyFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragments) {

        super(fm);
        mFragments = fragments;

    }

    @Override
    public Object instantiateItem(ViewGroup vg, int position) {
        return super.instantiateItem(vg, position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }
}

fragment_store.xml    fragment的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <include layout="@layout/fragment_special_offer_toolbar" />
    <TextView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="呵呵"
        android:textSize="20sp" />
</LinearLayout>
 
fragment_special_offer_toolbar.xml   toolbar的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        app:title="title"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:background="@color/colorAccent"
        android:navigationIcon="@drawable/icon_diamond_press"
        android:minHeight="?attr/actionBarSize">

<pre style="background-color:#ffffff;color:#000000;font-family:'Liberation Mono';font-size:10.5pt;"><pre name="code" class="html">        <ImageButton
            android:id="@+id/select"
            android:background="@drawable/icon_diamond"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_gravity="right"
            android:layout_marginRight="4dp"/><pre style="background-color:#ffffff;color:#000000;font-family:'Liberation Mono';font-size:10.5pt;"><pre name="code" class="html">    </android.support.v7.widget.Toolbar>



 </LinearLayout>

menu_main.xml     

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">

    <item
        android:id="@+id/overflow"
        android:title="展开"
        app:showAsAction="always"
        android:orderInCategory="100">

    </item>

</menu>
style.xml
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值