我正在开发一个包含许多活动的应用程序,并创建了自己的菜单(不想使用内置的菜单按钮),其中使用滑动抽屉作为在底部屏幕上包含我的菜单按钮。
我需要做的是使这个滑动抽屉在所有我的活动中都出现。
我尝试创建一个活动并将其内容视图设置为包含抽屉的XML文件,然后在所有其他活动中扩展该活动,但此解决方案无法正常工作。
那么有什么建议吗?
我正在开发一个包含许多活动的应用程序,并创建了自己的菜单(不想使用内置的菜单按钮),其中使用滑动抽屉作为在底部屏幕上包含我的菜单按钮。
我需要做的是使这个滑动抽屉在所有我的活动中都出现。
我尝试创建一个活动并将其内容视图设置为包含抽屉的XML文件,然后在所有其他活动中扩展该活动,但此解决方案无法正常工作。
那么有什么建议吗?
扩展是正确的方法。只需以正确的方式覆盖setContentView即可。 这是一个工作示例,但我使用了自定义的tabbar而不是抽屉式菜单:
像这样定义带有您的抽屉式菜单的布局:
这是act_layout.xml
<LinearLayout
...
android:orientation="vertical"
>
<YourDrawer
...
/>
<FrameLayout
android:id="@+id/act_content"
...
>
// Here will be all activity content placed
</FrameLayout>
</LinearLayout>
这将是包含所有其他布局的act_content框架的基本布局。 接下来,创建一个基本活动类,并执行以下操作:
public abstract class DrawerActivity extends Activity {
protected LinearLayout fullLayout;
protected FrameLayout actContent;
@Override
public void setContentView(final int layoutResID) {
// Your base layout here
fullLayout= (LinearLayout) getLayoutInflater().inflate(R.layout.act_layout, null);
actContent= (FrameLayout) fullLayout.findViewById(R.id.act_content);
// Setting the content of layout your provided to the act_content frame
getLayoutInflater().inflate(layoutResID, actContent, true);
super.setContentView(fullLayout);
// here you can get your drawer buttons and define how they
// should behave and what must they do, so you won't be
// needing to repeat it in every activity class
}
}
public abstract class SomeActivity extends DrawerActivity {
protected void onCreate(Bundle bundle) {
setContentView(R.layout.some_layout);
}
}
经过3年的努力,终于为那些可能没有完全按照奥洛夫先生的答案指导的人提供了这个重要问题的完整解决方案。
他制作层次视图的方法完全没问题,但有一些小错误可能会误导初学者开发人员。
因此,100%工作的解决方案应该像这样:
activity_drawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="@+id/drawer_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<YourDrawer
android:id="@+id/drawer_drawer"
android:layout_width="match_parent"
android:layout_height="fill_parent" >
</YourDrawer>
</RelativeLayout>
抽屉式导航活动(DrawerActivity.java)
public class DrawerActivity extends Activity {
protected RelativeLayout fullLayout;
protected FrameLayout frameLayout;
@Override
public void setContentView(int layoutResID) {
fullLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_drawer, null);
frameLayout = (FrameLayout) fullLayout.findViewById(R.id.drawer_frame);
getLayoutInflater().inflate(layoutResID, frameLayout, true);
super.setContentView(fullLayout);
//Your drawer content...
}
}
主活动.java
public class MainActivity extends DrawerActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
不要忘记在清单文件中声明 DrawerActivity。我知道这已经晚了两年,但是对于那些需要答案的人,这里有一个答案。Orlov先生给出了恰当的回答,只需要做一些调整。
另外:如果你想让滑动抽屉显示在布局的上方(显然!),那么请将滑动抽屉后面的frameLayout放在滑动抽屉之前。
setContentView(R.id.idl); }
} - Zak