[关闭]
@natsumi 2015-08-19T02:10:52.000000Z 字数 9782 阅读 2130

Toolbar代替ActionBar

Android


参考:
【1】http://m.blog.csdn.net/blog/jielundewode/41866477
【2】http://www.tuicool.com/articles/7BJBZb

1. 废掉ActionBar

1.1 方法(一)

AppTheme主题是在res/values/styles.xml中自定义主题AppTheme
AppTheme继承自AppTheme.BaseAppTheme.Base继承自Theme.AppCompat

  1. <resources>
  2. <!-- Base application theme. -->
  3. <style name="AppTheme" parent="AppTheme.Base">
  4. <!-- Customize your theme here. -->
  5. </style>
  6. <style name="AppTheme.Base" parent="Theme.AppCompat">
  7. <!--下面这2句就可以废掉ActionBar咯!-->
  8. <item name="windowActionBar">false</item>
  9. <item name="android:windowNoTitle">true</item>
  10. <!-- Actionbar color -->
  11. <item name="colorPrimary">@color/accent_material_dark</item>
  12. <!--Status bar color-->
  13. <item name="colorPrimaryDark">@color/accent_material_light</item>
  14. <!--Window color-->
  15. <item name="android:windowBackground">@color/dim_foreground_material_dark</item>
  16. </style>
  17. </resources>

在manifest文件中设置android:theme属性~

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.jikexueyuan.drawerlayoutusing" >
  4. <application
  5. android:allowBackup="true"
  6. android:icon="@mipmap/ic_launcher"
  7. android:label="@string/app_name"
  8. android:theme="@style/AppTheme" >
  9. <activity
  10. android:name=".MainActivity"
  11. android:label="@string/app_name" >
  12. <intent-filter>
  13. <action android:name="android.intent.action.MAIN" />
  14. <category android:name="android.intent.category.LAUNCHER" />
  15. </intent-filter>
  16. </activity>
  17. </application>
  18. </manifest>

1.2 方法(二)

不需要这两句:

  1. <item name="windowActionBar">false</item>
  2. <item name="android:windowNoTitle">true</item>

而是直接让AppTheme.Base继承自Theme.AppCompat.NoActionBar
当然如果不需要自定义主题的话可以直接在manifest里面写
android:theme="@style/Theme.AppCompat.NoActionBar"

2. 用ToolBar、DrawerLayout实现侧滑菜单

按照极客学院的视频用DrawerLayout实现侧滑菜单~但是 android.support.v4.app.ActionBarDrawerToggle已经不推荐使用了,所以尝试了v7的ActionBarDrawerToggle

ActionBarDrawerToggle的两个构造函数~这里选用第二个~

  1. ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes)
  2. ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)

2.1 Layout

一个纵向LinearLayout包裹ToolBar和DrawerLayout
DrawerLayout里依次包含主要内容视图和抽屉菜单视图~

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:app="http://schemas.android.com/apk/res-auto"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <android.support.v7.widget.Toolbar
  7. android:id="@+id/toolbar"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:background="?attr/colorPrimary"
  11. android:minHeight="?attr/actionBarSize"
  12. app:title="@string/app_name"
  13. app:subtitle="Hello, toolbar!"></android.support.v7.widget.Toolbar>
  14. <android.support.v4.widget.DrawerLayout
  15. android:id="@+id/drawer_layout"
  16. android:layout_width="match_parent"
  17. android:layout_height="match_parent">
  18. <!--the main content view 主要内容视图-->
  19. <FrameLayout
  20. android:id="@+id/content_frame"
  21. android:layout_width="match_parent"
  22. android:layout_height="match_parent"></FrameLayout>
  23. <!--the navigation view 抽屉菜单视图-->
  24. <ListView
  25. android:id="@+id/left_drawer"
  26. android:layout_width="240dp"
  27. android:layout_height="match_parent"
  28. android:layout_gravity="left"
  29. android:background="#999999"
  30. android:choiceMode="singleChoice"
  31. android:divider="@android:color/transparent"
  32. android:dividerHeight="0dp" />
  33. </android.support.v4.widget.DrawerLayout>
  34. </LinearLayout>

注意
如果用RelatvieLayout则需要去掉针对四个方向padding属性,并记得将Hello World设定layout_below="@+id/toolbar",否则会看到像下面这样的错误画面。
错误的画面

正确的代码是酱婶儿的!

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. xmlns:app="http://schemas.android.com/apk/res/com.xwh.toolbardemo"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. tools:context="com.xwh.toolbardemo.MainActivity" >
  7. <android.support.v7.widget.Toolbar
  8. android:id="@+id/toolbar"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:background="?attr/colorPrimary"
  12. android:minHeight="?attr/actionBarSize"
  13. app:title="@string/hello_world" />
  14. <TextView
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:layout_below="@+id/toolbar"
  18. android:text="@string/hello_world" />
  19. </RelativeLayout>

2.2 ToolBar的使用

ToolBar上的各部分的名称

  1. mTitle= (String) getTitle();
  2. mToolbar= (Toolbar) findViewById(R.id.toolbar);
  3. setSupportActionBar(mToolbar);//这句很重要~有了这个可以向AtyBar一样使用menu item
  4. mToolbar.setNavigationIcon(R.drawable.ic_drawer);
  5. mToolbar.setLogo(R.mipmap.ic_launcher);
  1. mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,mToolbar,R.string.drawer_open, R.string.drawer_close) {
  2. /** Called when a drawer has settled in a completely closed state. */
  3. public void onDrawerClosed(View view) {
  4. super.onDrawerClosed(view);
  5. mToolbar.setTitle(mTitle);
  6. invalidateOptionsMenu();//系统自动调用onPrepareOptionsMenu()
  7. }
  8. /** Called when a drawer has settled in a completely open state. */
  9. public void onDrawerOpened(View drawerView) {
  10. super.onDrawerOpened(drawerView);
  11. mToolbar.setTitle("请选择");
  12. invalidateOptionsMenu();
  13. }
  14. };

3. 完整代码

3.1 MainActivity.java

  1. package com.jikexueyuan.drawerlayoutusing;
  2. import android.app.Fragment;
  3. import android.app.FragmentManager;
  4. import android.content.Intent;
  5. import android.content.res.Configuration;
  6. import android.net.Uri;
  7. import android.os.Bundle;
  8. import android.os.PersistableBundle;
  9. import android.support.v4.widget.DrawerLayout;
  10. import android.support.v7.app.ActionBarActivity;
  11. import android.support.v7.app.ActionBarDrawerToggle;
  12. import android.support.v7.widget.Toolbar;
  13. import android.view.Menu;
  14. import android.view.MenuItem;
  15. import android.view.View;
  16. import android.widget.AdapterView;
  17. import android.widget.ArrayAdapter;
  18. import android.widget.ListView;
  19. import java.util.ArrayList;
  20. public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener{
  21. private Toolbar mToolbar;
  22. private DrawerLayout mDrawerLayout;
  23. private ListView mDrawerList;
  24. private ArrayList<String> menuLists;
  25. private ArrayAdapter<String> adapter;
  26. private ActionBarDrawerToggle mDrawerToggle;
  27. private String mTitle;
  28. @Override
  29. protected void onCreate(Bundle savedInstanceState) {
  30. super.onCreate(savedInstanceState);
  31. setContentView(R.layout.activity_main);
  32. mTitle= (String) getTitle();
  33. mToolbar= (Toolbar) findViewById(R.id.toolbar);
  34. setSupportActionBar(mToolbar);//这句很重要~有了这个可以向AtyBar一样使用menu item
  35. mToolbar.setNavigationIcon(R.drawable.ic_drawer);
  36. mToolbar.setLogo(R.mipmap.ic_launcher);
  37. mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout);
  38. mDrawerList= (ListView) findViewById(R.id.left_drawer);
  39. menuLists=new ArrayList<String>();
  40. for(int i=0;i<5;i++){
  41. menuLists.add("极客学院0"+i);
  42. }
  43. adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menuLists);
  44. mDrawerList.setAdapter(adapter);
  45. mDrawerList.setOnItemClickListener(this);
  46. mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,mToolbar,
  47. R.string.drawer_open, R.string.drawer_close) {
  48. /** Called when a drawer has settled in a completely closed state. */
  49. public void onDrawerClosed(View view) {
  50. super.onDrawerClosed(view);
  51. mToolbar.setTitle(mTitle);
  52. invalidateOptionsMenu();//系统自动调用onPrepareOptionsMenu()
  53. }
  54. /** Called when a drawer has settled in a completely open state. */
  55. public void onDrawerOpened(View drawerView) {
  56. super.onDrawerOpened(drawerView);
  57. mToolbar.setTitle("请选择");
  58. invalidateOptionsMenu();
  59. }
  60. };
  61. mDrawerLayout.setDrawerListener(mDrawerToggle);
  62. //开启ActionBar上的APP ICON功能//toolbar怎么办!!!
  63. // getActionBar().setDisplayHomeAsUpEnabled(true);
  64. // getActionBar().setHomeButtonEnabled(true);
  65. }
  66. @Override
  67. public boolean onPrepareOptionsMenu(Menu menu) {
  68. boolean isDrawerOpen=mDrawerLayout.isDrawerOpen(mDrawerList);
  69. menu.findItem(R.id.action_websearch).setVisible(!isDrawerOpen);
  70. return super.onPrepareOptionsMenu(menu);
  71. }
  72. @Override
  73. public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
  74. super.onPostCreate(savedInstanceState, persistentState);
  75. //需要将ActionBarDrawerToggle与DrawerLayout同步
  76. //将ActionBarDrawerToggle中的drawer图标设置为ActionBar中的home-button的icon
  77. mDrawerToggle.syncState();
  78. }
  79. @Override
  80. public void onConfigurationChanged(Configuration newConfig) {
  81. super.onConfigurationChanged(newConfig);
  82. mDrawerToggle.onConfigurationChanged(newConfig);//官方建议这样使用
  83. }
  84. @Override
  85. public boolean onCreateOptionsMenu(Menu menu) {
  86. // Inflate the menu; this adds items to the action bar if it is present.
  87. getMenuInflater().inflate(R.menu.menu_main, menu);
  88. return true;
  89. }
  90. @Override
  91. public boolean onOptionsItemSelected(MenuItem item) {
  92. // Handle action bar item clicks here. The action bar will
  93. // automatically handle clicks on the Home/Up button, so long
  94. // as you specify a parent activity in AndroidManifest.xml.
  95. int id = item.getItemId();
  96. //noinspection SimplifiableIfStatement
  97. switch (id){
  98. case R.id.action_websearch:
  99. Intent intent=new Intent();
  100. intent.setAction("android.intent.action.VIEW");
  101. Uri uri = Uri.parse("http://www.jikexueyuan.com");
  102. intent.setData(uri);
  103. startActivity(intent);
  104. break;
  105. }
  106. return super.onOptionsItemSelected(item);
  107. }
  108. @Override
  109. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  110. //动态插入一个fragment到framelayout中
  111. Fragment contentFragment=new ContentFragment();
  112. Bundle args=new Bundle();
  113. args.putString("text",menuLists.get(position));//参数传入Fragment
  114. contentFragment.setArguments(args);
  115. FragmentManager fm=getFragmentManager();
  116. fm.beginTransaction().replace(R.id.content_frame,contentFragment).commit();//展示新的fragment
  117. mDrawerLayout.closeDrawer(mDrawerList);//隐藏侧滑菜单
  118. }
  119. }

3.2 ContentFragment.java

  1. package com.jikexueyuan.drawerlayoutusing;
  2. import android.os.Bundle;
  3. import android.app.Fragment;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. import android.widget.TextView;
  8. /**
  9. * A simple {@link Fragment} subclass.
  10. */
  11. public class ContentFragment extends Fragment {
  12. private TextView textView;
  13. public ContentFragment() {
  14. // Required empty public constructor
  15. }
  16. @Override
  17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  18. Bundle savedInstanceState) {
  19. // Inflate the layout for this fragment
  20. View view=inflater.inflate(R.layout.fragment_content, container, false);
  21. textView= (TextView) view.findViewById(R.id.textview);
  22. String text=getArguments().getString("text");//接收传递进来的参数
  23. textView.setText(text);
  24. return view;
  25. }
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注