Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 關於android抽屜,navigation drawer

關於android抽屜,navigation drawer

編輯:關於Android編程

最近在做的一個項目需要用到一個側邊欄,我留意到了這玩意,但是這玩意是五月份才發布的,國內資料比較少。找來找去也沒找到什麼。就從官方下了一個例子,對著例子看,在自己項目中改來改去,把項目改的報錯不斷,也沒弄懂什麼原理,最後導致項目運行不起來了。我索性就仔細研究下這個抽屜,先自己對著官方的demo做.官方的開發頁是:

http://developer.android.com/design/patterns/navigation-drawer.html

這個東西主要的原理就是左邊是一個ListView,右邊是一個FrameLayout.(就是主內容):

看下這個文件:

activity_main.xml:


    
    <frameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    
    



再來一個左邊側邊欄的各個項的配置:

drawer_list_item.xml:




主內容配置文件:

fragment_planet.xml:





如果使用菜單的話,加入actionBar的menu:(在menu文件夾下)

main.xml:



    



再貼上String.xml:




    drawerexample
    Settings
    Hello world!
	 
        Mercury
        Venus
        Earth
        Mars
        Jupiter
        Saturn
        Uranus
        Neptune
    
     Open navigation drawer
     Close navigation drawer
     Web search
     Sorry, there\'s no web browser available


最後就是主activity了:

MainActivity.java

package com.example.drawerexample;


import java.util.Locale;



import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends Activity {
	private CharSequence mTitle;
	private CharSequence mDrawerTitle;
	private String[] mPlanetTitles;
	private ListView mDrawerList;
	private DrawerLayout mDrawerLayout;
	private ActionBarDrawerToggle mDrawerToggle;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mTitle = mDrawerTitle = getTitle();
		mPlanetTitles = getResources().getStringArray(R.array.planets_array);
		mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		// set a custom shadow that overlays the main content when the drawer opens
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
		// set up the drawer's list view with items and click listener
		mDrawerList.setAdapter(new ArrayAdapter(this, 
				R.layout.drawer_list_item,mPlanetTitles));
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		
		// enable ActionBar app icon to behave as action to toggle nav drawer
		getActionBar().setDisplayHomeAsUpEnabled(true);
		 getActionBar().setHomeButtonEnabled(true);
		 
		 // ActionBarDrawerToggle ties together the the proper interactions
	     // between the sliding drawer and the action bar app icon
		 mDrawerToggle = new ActionBarDrawerToggle(
				 this,                  /* host Activity */
	             mDrawerLayout,         /* DrawerLayout object */
	             R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
	             R.string.drawer_open,  /* "open drawer" description for accessibility */
	             R.string.drawer_close 
				 ){
			 public void onDrawerClosed(View view){
				 getActionBar().setTitle(mTitle);
				 invalidateOptionsMenu();// creates call to onPrepareOptionsMenu()
			 }
			 
			 public void onDrawerOpened(View drawerView){
				 getActionBar().setTitle(mDrawerTitle);
				 invalidateOptionsMenu();// creates call to onPrepareOptionsMenu()
			 }
		 };
		 mDrawerLayout.setDrawerListener(mDrawerToggle);
		 
		 if(savedInstanceState == null){
			 selectItem(0);
		 }
	}

	//action bar 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if the nav drawer is open,hide action items related to the content view
		boolean draweropen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_websearch).setVisible(!draweropen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(mDrawerToggle.onOptionsItemSelected(item)){
			return true;
		}
		// Handle action buttons
		switch (item.getItemId()) {
		case R.id.action_websearch:
			Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
			intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
			if(intent.resolveActivity(getPackageManager()) != null) {
				startActivity(intent);
			} else {
				Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
			}
			return true;
			
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	// The click listner for ListView in the navigation drawe 
	private class DrawerItemClickListener implements ListView.OnItemClickListener{
		@Override
		public void onItemClick(AdapterView parent, View view, int position,
				long id) {
			selectItem(position);
		}
	}
	
	private void selectItem(int position){
		// update the main content by replacing fragments
		Fragment fragment = new PlanetFragment();
		Bundle args = new Bundle();
		args.putInt(PlanetFragment.ARG_PLANET_NUMBER,position);
		fragment.setArguments(args);
		
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
		
		 // update selected item and title, then close the drawer
		mDrawerList.setItemChecked(position, true);
		setTitle(mPlanetTitles[position]);
		mDrawerLayout.closeDrawer(mDrawerList);
	}
	
	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}
	
	/**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */
	 @Override
	    protected void onPostCreate(Bundle savedInstanceState) {
	        super.onPostCreate(savedInstanceState);
	        // Sync the toggle state after onRestoreInstanceState has occurred.
	        mDrawerToggle.syncState();
	 }
	 
	 @Override
	    public void onConfigurationChanged(Configuration newConfig) {
	        super.onConfigurationChanged(newConfig);
	        // Pass any configuration change to the drawer toggls
	        mDrawerToggle.onConfigurationChanged(newConfig);
	    }
	

	/**
	 * FragMent出現在content_frame
	 */
	 public static class PlanetFragment extends Fragment {
	        public static final String ARG_PLANET_NUMBER = "planet_number";

	        public PlanetFragment() {
	            // Empty constructor required for fragment subclasses
	        }

			@Override
			public View onCreateView(LayoutInflater inflater,
				ViewGroup container, Bundle savedInstanceState) {
				View rootView = inflater.inflate(R.layout.fragment_planet, container,false);
				int i = getArguments().getInt(ARG_PLANET_NUMBER);
				String planet = getResources().getStringArray(R.array.planets_array)[i];
				int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()), 
						"drawable", getActivity().getPackageName());
				((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
				getActivity().setTitle(planet);
				return rootView;
			}
	        
	 }
}



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved