我正在编写一个 Android 应用程序来利用抽屉布局功能。我希望能够将抽屉布局用作整个应用程序中可用的导航工具。要使用抽屉布局,我在我的 Activity 布局 xml 文件中使用以下内容:
<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 -->
<LinearLayout
android:id="@+id/main_content_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="@+id/navigational_drawer"
android:layout_width="220dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#FFFFFF"/>
</android.support.v4.widget.DrawerLayout>
但是,我在将 DrawerLayout 包装在 PreferenceActivity 周围时遇到了很多困难。 PreferenceActivity 是一种我想保留的特殊 Activity ,因为它可以帮助我在我的应用程序中保持 Android 首选项的外观;也就是说,它使用 addPreferencesFromResource() 调用来加载首选项,而不使用 addContentView() 调用来加载 XML 文件;首选项资源通常包含不喜欢包装在 DrawerLayouts 中的 PreferenceScreen 标签。
有人必须处理这个问题,您是如何解决的?如果您的 Android 应用程序中有 PreferenceActivity 并且在同一 Activity 中有可用的 DrawerLayout,请分享您是如何做到的。任何帮助将非常感激。
编辑:如果我改变
<!-- The main content view -->
<LinearLayout
android:id="@+id/main_content_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
到
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
然后应用程序不会在加载 PreferenceActivity 时崩溃(因为 id“列表”与 Preference Activity 期望找到的内容相匹配);但是,抽屉没有显示。几乎就像 ListView“列表”下面的所有内容都被忽略了。
最佳答案
这花了我一段时间,但我能够为我的应用程序完成这项工作。我不知道这是否会有所不同,但我正在使用 HoloEverywhere
,所以我只假设这也适用于标准 PreferenceActivity
。
在我的 PreferenceActivity
中,当我覆盖所有版本的 setContentView()
以加载我的自定义 DrawerLayout
时,它与您的一样并且有一个 ListView
与 list
的标准 android id。在最后一个方法中,我确保在调用 super.setContentView()
之后调用 onContentChanged()
:
@Override
public void setContentView(int layoutResID)
{
setContentView( getLayoutInflater().inflate( layoutResID ) );
}
@Override
public void setContentView(View view)
{
setContentView( view, new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) );
}
@Override
public void setContentView(View view, LayoutParams params)
{
// inflate the drawer layout
super.setContentView( R.layout.navigation_drawer_base_layout );
DrawerLayout dl = findViewById(R.id.drawer_layout);
// do stuff here initialize the DrawerLayout like add a DrawerToggle, etc
...STUFF
// Call onContentsChanged() to let the Activity know it needs to refresh itself.
onContentChanged();
}
在 onBuildHeaders()
中,我仍然调用 loadHeadersFromResource()
为不同的 PreferenceScreen
创建所有 Header
>s.
关于android - 如何在 Android 应用程序中将 DrawerLayout 包装在 PreferenceActivity 周围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16762656/