ActionBar除了显示Action Item 外,还能显示普通的ui组件
2种方式添加Action View
1.指定ActionView的实现类
2.指定ActionView对应的视图资源
实现代码:
1 package com.example.administrator.myapplication; 2 3 import android.support.v4.view.MenuItemCompat; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.Menu; 7 import android.view.MenuInflater; 8 9 public class MainActivity extends AppCompatActivity { 10 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.activity_main); 15 } 16 17 @Override 18 public boolean onCreateOptionsMenu(Menu menu) { 19 MenuInflater inflater = new MenuInflater(this); 20 inflater.inflate(R.menu.menu_main,menu);
//重要代码,照着书上写的话,这些ActionView显示不出来,网上找的这个解决方法,目前有效 21 MenuItemCompat.setShowAsAction(menu.findItem(R.id.search),MenuItemCompat.SHOW_AS_ACTION_ALWAYS); 22 MenuItemCompat.setShowAsAction(menu.findItem(R.id.progess),MenuItemCompat.SHOW_AS_ACTION_ALWAYS); 23 return super.onCreateOptionsMenu(menu); 24 } 25 }
资源文件代码:menu文件下的
1 <?xml version="1.0" encoding="utf-8"?> 2 <menu xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto"> 4 <item android:title="@string/app_name" 5 android:id="@+id/search" 6 android:orderInCategory="100" 7 app:showAsAction="always" 8 android:actionViewClass="android.widget.SearchView"> 9 </item> 10 <item android:title="@string/app_name" 11 android:id="@+id/progess" 12 android:orderInCategory="100" 13 app:showAsAction="always" 14 android:actionLayout="@layout/clock"> 15 16 </item> 17 </menu>