Menu综合运用
To read first:
ActionBar http://www.cnblogs.com/iMirror/p/4077426.html
Menu http://www.cnblogs.com/iMirror/p/4076864.html
<1>Menu用icon显示, 多余的缩进overflow
实现Navigating Up with App icon
<2> Action View实现SearchView Menu, 并学会 绑定监听器
<3> 增加Action Provider
<4>Navigation Tabs to show different Fragment
<5> Show in the landscape
Code:
//MenuTest.java package mirror.android.menutest; import java.lang.reflect.Field; import java.lang.reflect.Method; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.ActionBar.TabListener; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.MenuItemCompat.OnActionExpandListener; import android.view.Menu; import android.view.MenuItem; import android.view.ViewConfiguration; import android.view.Window; import android.widget.SearchView; import android.widget.SearchView.OnQueryTextListener; import android.widget.ShareActionProvider; import android.widget.TextView; import android.widget.Toast; public class MenuTest extends Activity{ private TextView textView; private ShareActionProvider mShareActionProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_test); textView = (TextView)findViewById(R.id.tv_show); //let overflow show no matter physical "Menu" key exists or not setOverflowShowingAlways(); // to add Navigating Up to the action Bar ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); // setup action bar for Tab actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab() .setText("artist") //.setTabListener(new MytabListener(new Artist()))); .setTabListener(new MytabListener(this, "artist", Artist.class))); actionBar.addTab(actionBar.newTab() .setText("album") //.setTabListener(new MytabListener(new Album()))); .setTabListener(new MytabListener(this, "album", Album.class))); actionBar.addTab(actionBar.newTab() .setText("song") //.setTabListener(new MytabListener(new Song()))); .setTabListener(new MytabListener(this, "song", Song.class))); } //overflow is shown or not depends on hardware.if Physical "Menu" key exsit, the overflow menu will not appear. //This method is to show overflow no matter Physical "Menu" keys exsits or not private void setOverflowShowingAlways() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField; menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); menuKeyField.setAccessible(true); try { menuKeyField.setBoolean(config, false); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } catch (NoSuchFieldException e) { e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_test, menu); /**search Region**/ MenuItem searchItem = menu.findItem(R.id.search); // View with "collapseActionView" attribute, and set // the setOnActionExpandListener() method to listen to its Expand and Collapse action // commonly to show different fragment in this two different state MenuItemCompat.setOnActionExpandListener(searchItem, new OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { Toast.makeText(getApplication(), "Search Expand", Toast.LENGTH_SHORT).show(); // Return true to collapse action view return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { Toast.makeText(getApplication(), "Search Collapse", Toast.LENGTH_SHORT).show(); // Return true to expand action view return true; } }); // to edit SearchView properties SearchView searchView = (SearchView)MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { Toast.makeText(getApplication(), query , Toast.LENGTH_SHORT).show(); return true; } @Override public boolean onQueryTextChange(String newText) { textView.setText(newText); return true; } }); /**share region**/ // set up ShareActionProvider`s default share intent MenuItem shareItem = menu.findItem(R.id.share); mShareActionProvider = (ShareActionProvider)shareItem.getActionProvider(); mShareActionProvider.setShareIntent(new Intent(Intent.ACTION_SEND).setType("image/*")); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case android.R.id.home: Toast.makeText(getApplication(), "Add Navigating up method", Toast.LENGTH_SHORT).show(); break; case R.id.market1: Toast.makeText(getApplication(), "market1", Toast.LENGTH_SHORT).show(); break; case R.id.market2: Toast.makeText(getApplication(), "market2", Toast.LENGTH_SHORT).show(); break; case R.id.email: Toast.makeText(getApplication(), "email", Toast.LENGTH_SHORT).show(); break; case R.id.map: Toast.makeText(getApplication(), "map", Toast.LENGTH_SHORT).show(); break; default: break; } return super.onOptionsItemSelected(item); } // Method to let overflow menu to show icons instead of just text @Override public boolean onMenuOpened(int featureId, Menu menu) { if(featureId == Window.FEATURE_ACTION_BAR && menu != null){ if(menu.getClass().getSimpleName().equals("MenuBuilder")){ try { Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible",Boolean.TYPE); m.setAccessible(true); m.invoke(menu, true); } catch (Exception e) { } } } return super.onMenuOpened(featureId, menu); } // Tab Listener public class MytabListener implements TabListener{ private Fragment fragment; private final Activity mActivity; private final String mTag; private final Class mClass; //@param activity The host Activity, used to instantiate the fragment //@param tag The identifier tag for the fragment //@param clz The fragment's Class, used to instantiate the fragment public MytabListener(Activity activity, String tag, Class clz){ this.mActivity = activity; this.mTag = tag; this.mClass = clz; } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { if(fragment == null){ // If not initialized before, instantiate and add it to the activity fragment = Fragment.instantiate(mActivity, mClass.getName()); ft.add(android.R.id.content,fragment,mTag); } else{ //Log.d("d",fragment.getClass().getName()); could get the name of fragment ft.attach(fragment); } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (fragment != null) { // Detach the fragment, because another one is being attached ft.detach(fragment); } } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } } }
//Artist.java the same as Song.java and Album.java package mirror.android.menutest; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class Artist extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.artist, container, false); return rootView; } } //artist.xml the same as song.xml and album.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Artist" /> </RelativeLayout>
//menu_test.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="mirror.android.menutest.MenuTest" > <item android:id="@+id/search" android:title="search" android:icon="@drawable/search" android:actionViewClass="android.widget.SearchView" android:showAsAction="always|collapseActionView"/> <item android:id="@+id/share" android:title="share" android:showAsAction="ifRoom" android:actionProviderClass="android.widget.ShareActionProvider"/> <item android:id="@+id/market" android:title="market" android:icon="@drawable/market" android:showAsAction="ifRoom"> <menu> <item android:id="@+id/market1" android:title="market1"/> <item android:id="@+id/market2" android:title="market2"/> </menu> </item> <item android:id="@+id/email" android:icon="@drawable/email" android:title="email" android:showAsAction="collapseActionView"/> <item android:id="@+id/map" android:icon="@drawable/map" android:title="map" android:showAsAction="collapseActionView"/> </menu>