Android学习 - Navigation Drawer

NavigationDrawer是Android团对在2013 google IO大会期间更新的Support库(V13)中新加入的重要的功能。实现Navigation Drawer需要使用最新支持库(V13)的DrawerLayout。Navigation Drawer的设计指南请参考。Navigation Drawer是从屏幕的左侧滑出,显示应用导航的视图。官方是这样定义的:

The navigation drawer is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the user swipes a finger from the left edge of the screen or, while at the top level of the app, the user touches the app icon in the action bar.

NavigationDrawer不同于SlidingDrawer,它不存在可以拖动的handle;它也不同于SlidingMenu,Navigation Drawer滑出时主屏幕视图不一定。Navigation Drawer是覆盖在主视图上的。NavigationDrawer design guide:

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

Create a Drawer Layout

创建Navigation Drawer需要用DrawerLayout 作为界面根控件。在DrawerLayout里面第一个View为当前界面主内容;第二个和第三个View为Navigation Drawer内容。如果当前界面只需要一个Navigation Drawer,则第三个View可以省略。下面的例子中DrawerLayout里面包含两个View,第一个FrameLayout中是当前界面主要内容显示区域;第二个ListView为Navigation Drawer内容。

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!-- The main content view -->

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />

</android.support.v4.widget.DrawerLayout>

上面的代码中有如下几点需要注意:

1、显示界面主要内容的View(上面的 FrameLayout)必须为DrawerLayout的第一个子View,原因在于XML布局文件中的View顺序为Android系统中的z-ordering顺序,而Navigation Drawer必须出现在内容之上。

2、显示界面内容的View宽度和高度设置为和父View一样,原因在于当Navigation Drawer不可见的时候,界面内容代表整个界面UI。

3、Navigation Drawer(上面的ListView必须使用android:layout_gravity属性设置水平的gravity值。如果要支持right-to-left(RTL从右向左阅读)语言用“start”代替“left”(当在RTL语言运行时候,菜单出现在右侧)。

4、抽屉菜单的宽度为dp单位而高度和父View一样。抽屉菜单的宽度应该不超过320dp,这样用户可以在菜单打开的时候看到部分内容界面。

Initialize the DrawerList

在您的Activity中需要先初始化Navigation Drawer内容,根据您的应用需要Navigation Drawer的内容可能不是ListView,可以使用其他View。在上面的示例中,我们需要给Navigation Drawer的ListView设置一个Adapter来提供数据。如下所示:

public class MainActivity extends Activity {

	private String[] mPlanetTitles;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mPlanetTitles = getResources().getStringArray(R.array.planets_array);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		// Set the adapter for the list view
		mDrawerList.setAdapter(new ArrayAdapter<String>(this,
				R.layout.drawer_list_item, mPlanetTitles));
		// Set the list's click listener
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
	}
}

上面的代码调用了 setOnItemClickListener() 函数来接受Navigation Drawer点击事件。下面会介绍如何通过点击Navigation Drawer显示主界面内容。

Handle NavigationClick Events

当用户选择NavigationDrawer List中的条目时,系统会调用OnItemClickListener的 onItemClick()函数。 根据您的应用需要,onItemClick函数的实现方式可能不同。下面的示例中,选择Navigation Drawer条目会在程序主界面中插入不同的 Fragment 。

private class DrawerItemClickListener implements
		ListView.OnItemClickListener {
	@Override
	public void onItemClick(AdapterView parent, View view, int position, long id) {
		selectItem(position);
	}
}

/** Swaps fragments in the main content view */
private void selectItem(int position) {
	// Create a new fragment and specify the planet to show based on
	// position
	Fragment fragment = new PlanetFragment();
	Bundle args = new Bundle();
	args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
	fragment.setArguments(args);
	// Insert the fragment by replacing any existing fragment
	FragmentManager fragmentManager = getFragmentManager();
	fragmentManager.beginTransaction()
			.replace(R.id.content_frame, fragment).commit();
	// Highlight the selected item, update the title, and close the drawer
	mDrawerList.setItemChecked(position, true);
	setTitle(mPlanetTitles[position]);
	mDrawerLayout.closeDrawer(mDrawerList);
}

@Override
public void setTitle(CharSequence title) {
	mTitle = title;
	getActionBar().setTitle(mTitle);
}

Listen for Open andClose Events

如果需要监听菜单打开关闭事件,则需要调用DrawerLayout类的setDrawerListener()函数,参数为DrawerLayout.DrawerListener接口的实现该接口提供了菜单打开关闭等事件的回调函数,例如onDrawerOpened()onDrawerClosed()

如果您的Activity使用了action bar,则您可以使用Support库提供的 ActionBarDrawerToggle 类,该类实现了 DrawerLayout.DrawerListener接口,并且您还可以根据需要重写相关的函数。该类实现了菜单和Action bar相关的操作。

根据在Navigation Drawer设计指南中的介绍,当菜单显示的时候您应该根据情况隐藏ActionBar上的功能菜单并且修改ActionBar的标题。下面的代码演示了如何重写ActionBarDrawerToggle类的相关函数来实现该功能。

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }
    /* 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);
    }
}

Open and Close withthe App Icon

用户可以从屏幕边缘滑动来打开Navigation Drawer,如果您使用了action bar,应该让用户通过点击应用图标也可以打开抽屉菜单。并且应用图标也应该使用一个特殊的图标来指示抽屉菜单。您可以使用 ActionBarDrawerToggle 类来实现这些功能。

使用 ActionBarDrawerToggle ,先通过其构造函数来创建该对象,构造函数需要如下参数:

1)显示Navigation Drawer的 Activity 对象

2) DrawerLayout 对象

3)一个用来指示Navigation Drawer的 drawable资源

4)一个用来描述打开Navigation Drawer的文本(用于支持可访问性)。

5)一个用来描述关闭Navigation Drawer的文本(用于支持可访问性)。

无论你是否继承 ActionBarDrawerToggle 来实现Navigation Drawer监听器,您都需要在Activity的生命周期函数中调用ActionBarDrawerToggle 的一些函数。如下所示:

public class MainActivity extends Activity {
	private DrawerLayout mDrawerLayout;
	private ActionBarDrawerToggle mDrawerToggle;

	public void onCreate(Bundle savedInstanceState) {
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description */
		R.string.drawer_close /* "close drawer" description */
		) {
			/** Called when a drawer has settled in a completely closed state. */
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
			}

			/** Called when a drawer has settled in a completely open state. */
			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
			}
		};
		// Set the drawer toggle as the DrawerListener
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
	}

	@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);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Pass the event to ActionBarDrawerToggle, if it returns
		// true, then it has handled the app icon touch event
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle your other action bar items...
		return super.onOptionsItemSelected(item);
	}
}

Navigation Drawer ForAndroid API 7

Creatinga Navigation Drawer中使用的Navigation Drawer的android:minSdkVersion="14",现在AndroidAPI Version 小于14的还有30%左右呢。Android版本的占有量可参考:

http://developer.android.com/about/dashboards/index.html#Platform


Android PlatformVersion

我们的应用为了适配不同的版本,需要降低minSdkVersion,作者一般适配SDK到API 7。这一篇博文也是把Creatinga Navigation Drawer的例子适配到API 7 。例子中降低API最主要的修改ActionBar,Action Bar是API 11才出现的,适配到API 7,我们使用了actionbarsherlock。

修改后的代码:

public class MainActivity extends SherlockFragmentActivity {
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] mPlanetTitles;

	@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<String>(this,
				R.layout.drawer_list_item, mPlanetTitles));
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		// enable ActionBar app icon to behave as action to toggle nav drawer
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().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 /* "close drawer" description for accessibility */
		) {
			/** Called when a drawer has settled in a completely closed state. */
			public void onDrawerClosed(View view) {
				getSupportActionBar().setTitle(mTitle);
			}

			/** Called when a drawer has settled in a completely open state. */
			public void onDrawerOpened(View drawerView) {
				getSupportActionBar().setTitle(mDrawerTitle);
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		if (savedInstanceState == null) {
			selectItem(0);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.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) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		// if (mDrawerToggle.onOptionsItemSelected(item)) {
		// return true;
		// }
		// Handle action buttons
		switch (item.getItemId()) {
		case android.R.id.home:
			handleNavigationDrawerToggle();
			return true;
		case R.id.action_websearch:
			// create intent to perform web search for this planet
			Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
			intent.putExtra(SearchManager.QUERY, getSupportActionBar()
					.getTitle());
			// catch event that there's no activity to handle intent
			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);
		}
	}

	private void handleNavigationDrawerToggle() {
		if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			mDrawerLayout.openDrawer(mDrawerList);
		}
	}

	/* The click listner for ListView in the navigation drawer */
	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 = getSupportFragmentManager();
		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;
		getSupportActionBar().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 that appears in the "content_frame", shows a planet
	 */
	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;
		}
	}
}

如果只修改JAVA代码,运行应用还是会出现异常:

08-13 13:26:15.909: E/AndroidRuntime(6832): FATAL EXCEPTION: main
08-13 13:26:15.909: E/AndroidRuntime(6832): android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.LayoutInflater.createView(LayoutInflater.java:518)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.LayoutInflater.inflate(LayoutInflater.java:386)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:332)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.AbsListView.obtainView(AbsListView.java:1495)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1216)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.ListView.onMeasure(ListView.java:1127)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.View.measure(View.java:8335)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.RelativeLayout.measureChild(RelativeLayout.java:566)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:381)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.View.measure(View.java:8335)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.View.measure(View.java:8335)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.View.measure(View.java:8335)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.View.measure(View.java:8335)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.ViewRoot.performTraversals(ViewRoot.java:843)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1892)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.os.Looper.loop(Looper.java:130)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.app.ActivityThread.main(ActivityThread.java:3835)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at java.lang.reflect.Method.invokeNative(Native Method)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at java.lang.reflect.Method.invoke(Method.java:507)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at dalvik.system.NativeStart.main(Native Method)
08-13 13:26:15.909: E/AndroidRuntime(6832): Caused by: java.lang.reflect.InvocationTargetException
08-13 13:26:15.909: E/AndroidRuntime(6832):     at java.lang.reflect.Constructor.constructNative(Native Method)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.LayoutInflater.createView(LayoutInflater.java:505)
08-13 13:26:15.909: E/AndroidRuntime(6832):     ... 32 more
08-13 13:26:15.909: E/AndroidRuntime(6832): Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x2
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:463)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.view.View.<init>(View.java:1978)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.TextView.<init>(TextView.java:350)
08-13 13:26:15.909: E/AndroidRuntime(6832):     at android.widget.TextView.<init>(TextView.java:343)
08-13 13:26:15.909: E/AndroidRuntime(6832):     ... 35 more

这个异常是drawer_list_item.xml文件的内容产生的,drawer_list_item.xml内容:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:gravity="center_vertical"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:textColor="#fff" />

而在API 14之前的版本中,下面的三个属性会报异常:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:textAppearance="?android:attr/textAppearanceListItemSmall" />

如果想适配更低的版本需要做如下的修改:

1)修改drawer_list_item.xml文件,使用自定义的属性

<?xml version="1.0" encoding="UTF-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/myapp_activatedBackgroundIndicator"
    android:gravity="center_vertical"
    android:minHeight="?attr/myapp_listPreferredItemHeightSmall"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textAppearance="?attr/myapp_textAppearanceListItemSmall" />

2)在values/attrs.xml文件中声明自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="AppTheme">

        <!-- Attributes below are needed to support the navigation drawer on Android 3.x. -->
        <!-- A smaller, sleeker list item height. -->
        <attr name="myapp_listPreferredItemHeightSmall" format="dimension" />
        <!-- Drawable used as a background for activated items. -->
        <attr name="myapp_activatedBackgroundIndicator" format="reference" />
        <!-- The preferred TextAppearance for the primary text of small list items. -->
        <attr name="myapp_textAppearanceListItemSmall" format="reference" />
    </declare-styleable>

</resources>

3)在values-11/styles.xml文件中添加

<!--
  Base application theme, dependent on API level. This theme is replaced
  by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="Theme.Sherlock.Light.DarkActionBar">

    <!--
      Theme customizations available in newer API levels can go in
      res/values-vXX/styles.xml, while customizations related to
      backward-compatibility can go here.
    -->
    <!--
    Implementation of attributes needed for the navigation drawer
     as the default implementation is based on API-14.
    -->
    <item name="myapp_listPreferredItemHeightSmall">48dip</item>
    <item name="myapp_textAppearanceListItemSmall">@style/MyappDrawerMenu</item>
    <item name="myapp_activatedBackgroundIndicator">@android:color/transparent</item>
</style>

<style name="MyappDrawerMenu">
    <item name="android:textSize">16sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@android:color/black</item>
</style>

4)在values-v14/styles.xml文件中添加

<!--
    Base application theme for API 14+. This theme completely replaces
    AppBaseTheme from BOTH res/values/styles.xml and
    res/values-v11/styles.xml on API 14+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">

    <!-- For API-14 and above the default implementation of the navigation drawer menu is used. Below APU-14 a custom implementation is used. -->
    <item name="myapp_listPreferredItemHeightSmall">?android:attr/listPreferredItemHeightSmall</item>
    <item name="myapp_textAppearanceListItemSmall">?android:attr/textAppearanceListItemSmall</item>
    <item name="myapp_activatedBackgroundIndicator">?android:attr/activatedBackgroundIndicator</item>
</style>

经过上面步骤,运行成功,这样上一篇的例子就能很好的适配到API 7了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值