[英]Same Navigation Drawer in different Activities
我制作了一個可用的導航抽屜,就像developer.android.com網站上的教程中所示。 但是現在,我想使用一個導航抽屜,我在 NavigationDrawer.class 中為應用程序中的多個活動創建了它。
我的問題是,如果這里有人可以制作一個小教程,其中解釋了如何將一個導航抽屜用於多個活動。
我首先閱讀了這個答案Android Navigation Drawer on multiple Activity
但它對我的項目不起作用
public class NavigationDrawer extends Activity {
public DrawerLayout drawerLayout;
public ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.menu);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
listItems = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, android.R.id.text,
listItems));
drawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
drawerClickEvent(pos);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
在此活動中,我想擁有導航抽屜,因此我擴展了“導航抽屜”,而在其他一些活動中,我想使用相同的導航抽屜
public class SampleActivity extends NavigationDrawer {...}
如果你想要一個導航抽屜,你應該使用片段。 我上周學習了本教程,效果很好:
http://developer.android.com/training/implementing-navigation/nav-drawer.html
您還可以從本教程下載示例代碼,以了解如何執行此操作。
無碎片:
這是您的 BaseActivity 代碼:
public class BaseActivity extends Activity
{
public DrawerLayout drawerLayout;
public ListView drawerList;
public String[] layers;
private ActionBarDrawerToggle drawerToggle;
private Map map;
protected void onCreate(Bundle savedInstanceState)
{
// R.id.drawer_layout should be in every activity with exactly the same id.
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(R.string.menu);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
layers = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.left_drawer);
View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null);
drawerList.addHeaderView(header, null, false);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, android.R.id.text1,
layers));
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.drawer_list_footer, null, false);
drawerList.addFooterView(footerView);
drawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
map.drawerClickEvent(pos);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
需要有導航抽屜的所有其他活動應該擴展這個活動而不是活動本身,例如:
public class AnyActivity extends BaseActivity
{
//Because this activity extends BaseActivity it automatically has the navigation drawer
//You can just write your normal Activity code and you don't need to add anything for the navigation drawer
}
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 -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Put what you want as your normal screen in here, you can also choose for a linear layout or any other layout, whatever you prefer -->
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
編輯:
我自己也遇到了一些困難,所以如果您遇到 NullPointerExceptions,這里有一個解決方案。 在 BaseActivity 中,將 onCreate 函數更改為protected void onCreateDrawer()
。 其余的可以保持不變。 在擴展 BaseActivity 的活動中,按以下順序放置代碼:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
super.onCreateDrawer();
這幫助我解決了我的問題,希望它有幫助!
如果您有任何問題,請隨時提出,這就是您可以創建具有多個活動的導航抽屜的方法。
編輯2:
正如@GregDan 所說,你的BaseActivity
也可以覆蓋setContentView()
並在那里調用 onCreateDrawer :
@Override
public void setContentView(@LayoutRes int layoutResID)
{
super.setContentView(layoutResID);
onCreateDrawer() ;
}
我找到了最好的實現。 它位於Google I/O 2014應用程序中。
他們使用與凱文相同的方法。 如果你能從 I/O 應用程序中所有不需要的東西中抽象出來,你就可以提取你需要的一切,谷歌保證這是導航抽屜模式的正確用法。 每個活動都可以選擇將DrawerLayout
作為其主要布局。 有趣的部分是如何導航到其他屏幕。 它在BaseActivity
是這樣實現的:
private void goToNavDrawerItem(int item) {
Intent intent;
switch (item) {
case NAVDRAWER_ITEM_MY_SCHEDULE:
intent = new Intent(this, MyScheduleActivity.class);
startActivity(intent);
finish();
break;
這與通過片段事務替換當前片段的常見方式不同。 但用戶沒有發現視覺差異。
所以這個答案晚了幾年,但有人可能會欣賞它。 Android 為我們提供了一個新的小部件,它使使用一個導航抽屜和多個活動變得更容易。
android.support.design.widget.NavigationView 是模塊化的,在菜單文件夾中有自己的布局。 您使用它的方式是按以下方式包裝 xml 布局:
Root Layout 是一個 android.support.v4.widget.DrawerLayout,它包含兩個子項:一個<include ... />
用於正在包裝的布局(參見 2)和一個 android.support.design.widget.NavigationView。
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"> <include layout="@layout/app_bar_main" android:layout_width="match_parent" android:layout_height="match_parent" /> <android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" />
nav_header_main 只是一個 LinearLayout,你的 Navigation Drawar 的標題的方向 = 垂直。
activity_main_drawer 是 res/menu 目錄中的菜單 xml。 它可以包含您選擇的項目和組。 如果您使用 AndroidStudio Gallery,向導將為您制作一個基本的庫,您可以查看您的選項。
應用欄布局現在通常是一個 android.support.design.widget.CoordinatorLayout ,這將包括兩個子項:一個 android.support.design.widget.AppBarLayout(包含一個 android.support.v7.widget.Toolbar)和一個<include ... >
用於您的實際內容(參見 3)。
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="yourpackage.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main" />
內容布局可以是您想要的任何布局。 這是包含活動主要內容的布局(不包括導航抽屜或應用欄)。
現在,關於所有這些很酷的事情是,您可以將每個活動包裝在這兩個布局中,但讓您的 NavigationView(參見步驟 1)始終指向 activity_main_drawer(或其他任何內容)。 這意味着您將在所有活動中擁有相同的 (*) Navigation Drawer。
在一組活動中重用通用導航抽屜的最簡單方法
app_base_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<FrameLayout
android:id="@+id/view_stub"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/menu_test"
/>
</android.support.v4.widget.DrawerLayout>
AppBaseActivity.java
/*
* This is a simple and easy approach to reuse the same
* navigation drawer on your other activities. Just create
* a base layout that conains a DrawerLayout, the
* navigation drawer and a FrameLayout to hold your
* content view. All you have to do is to extend your
* activities from this class to set that navigation
* drawer. Happy hacking :)
* P.S: You don't need to declare this Activity in the
* AndroidManifest.xml. This is just a base class.
*/
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
public abstract class AppBaseActivity extends AppCompatActivity implements MenuItem.OnMenuItemClickListener {
private FrameLayout view_stub; //This is the framelayout to keep your content view
private NavigationView navigation_view; // The new navigation view from Android Design Library. Can inflate menu resources. Easy
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private Menu drawerMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.app_base_layout);// The base layout that contains your navigation drawer.
view_stub = (FrameLayout) findViewById(R.id.view_stub);
navigation_view = (NavigationView) findViewById(R.id.navigation_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 0, 0);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerMenu = navigation_view.getMenu();
for(int i = 0; i < drawerMenu.size(); i++) {
drawerMenu.getItem(i).setOnMenuItemClickListener(this);
}
// and so on...
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
/* Override all setContentView methods to put the content view to the FrameLayout view_stub
* so that, we can make other activity implementations looks like normal activity subclasses.
*/
@Override
public void setContentView(int layoutResID) {
if (view_stub != null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
View stubView = inflater.inflate(layoutResID, view_stub, false);
view_stub.addView(stubView, lp);
}
}
@Override
public void setContentView(View view) {
if (view_stub != null) {
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
view_stub.addView(view, lp);
}
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
if (view_stub != null) {
view_stub.addView(view, params);
}
}
@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);
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
// handle it
break;
case R.id.item2:
// do whatever
break;
// and so on...
}
return false;
}
}
對於其他想要做原始海報要求的人,請考慮像凱文所說的那樣使用片段。 這是一個關於如何做到這一點的優秀教程:
https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer
如果您選擇使用活動而不是片段,您將遇到每次導航到新活動時都會重新創建導航抽屜的問題。 這會導致每次導航抽屜的渲染丑陋/緩慢。
我的建議是:根本不要使用活動,而是使用片段,並在您顯示第一個片段的容器(例如線性布局)中替換它們。
該代碼可在 Android 開發者教程中找到,您只需要自定義即可。
http://developer.android.com/training/implementing-navigation/nav-drawer.html
建議您應該在您的應用程序中使用越來越多的片段,並且您的應用程序本地應該只有四個基本活動,除了外部活動(例如 FacebookActivity),您在 AndroidManifest.xml 中提到:
SplashActivity:不使用片段,使用全屏主題。
LoginSignUpActivity:完全不需要NavigationDrawer,也沒有后退按鈕,所以只需使用普通工具欄,但至少需要3或4個片段。 使用無操作欄主題
HomeActivity 或 DashBoard Activity:使用無操作欄主題。 在這里你需要導航抽屜,接下來的所有屏幕都將是片段或嵌套片段,直到葉子視圖,共享抽屜。 在此活動中,所有設置、用戶配置文件等都將作為片段出現在這里。 這里的片段不會被添加到后台堆棧中,而是會從抽屜菜單項中打開。 在需要返回按鈕而不是抽屜的片段的情況下,下面有第四種活動。
沒有抽屜的活動。 此活動頂部有一個后退按鈕,其中的片段將共享相同的操作欄。 這些片段將被添加到后台堆棧中,因為會有導航歷史記錄。
[有關進一步指導,請參閱: https : //stackoverflow.com/a/51100507/787399 ]
快樂編碼!!
在 baseactivity 中更新此代碼。 並且不要忘記在您的活動 xml 中包含 drawer_list_header。
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.drawer_list_header);
並且不要在您的活動中使用 request() 。 但是在單擊圖像時仍然看不到抽屜……並且通過拖動它可以在沒有列表項的情況下看到。 我嘗試了很多但沒有成功。 為此需要一些鍛煉...
通過@Kevin van Mierlo 的回答,您還可以實現多個抽屜。 例如,位於左側(開始)的默認菜單和位於右側的另一個可選菜單,僅在加載確定片段時顯示。
我已經能夠做到這一點。
package xxxxxx;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.widget.SearchView;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class loginhome extends AppCompatActivity {
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
// Make sure to be using android.support.v7.app.ActionBarDrawerToggle version.
// The android.support.v4.app.ActionBarDrawerToggle has been deprecated.
private ActionBarDrawerToggle drawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginhome);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.nav_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_first_fragment:
Toast.makeText(getApplicationContext(),"First fragment",Toast.LENGTH_SHORT).show();
FirstFragment fragment = new FirstFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.nav_second_fragment:
Toast.makeText(getApplicationContext(),"Second fragment",Toast.LENGTH_SHORT).show();
SecondFragment fragment2 = new SecondFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.frame,fragment2);
fragmentTransaction2.commit();
return true;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open, R.string.drawer_close){
@Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
將此用於您的 toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:elevation="4dp"
android:id="@+id/toolbar"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
>
</android.support.v7.widget.Toolbar>
如果要使用,請將此用於導航標題
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="192dp"
android:background="?attr/colorPrimaryDark"
android:padding="16dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical"
android:gravity="bottom">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:id="@+id/navhead"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:textColor="#ffffff"
android:text="tanya"
android:textSize="14sp"
android:textStyle="bold"
/>
<TextView
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_marginLeft="16dp"
android:layout_marginTop="5dp"
android:text="tanya.com"
android:textSize="14sp"
android:textStyle="normal"
/>
</LinearLayout>
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_below="@+id/imageView"
android:layout_marginTop="15dp"
android:src="@drawable/face"
android:id="@+id/circleView"
/>
</RelativeLayout>
我在 Kotlin 中這樣做:
open class BaseAppCompatActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
protected lateinit var drawerLayout: DrawerLayout
protected lateinit var navigationView: NavigationView
@Inject
lateinit var loginService: LoginService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d("BaseAppCompatActivity", "onCreate()")
App.getComponent().inject(this)
drawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
navigationView = findViewById(R.id.nav_view) as NavigationView
navigationView.setNavigationItemSelectedListener(this)
val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
toggle.isDrawerIndicatorEnabled = true
val navigationViewHeaderView = navigationView.getHeaderView(0)
navigationViewHeaderView.login_txt.text = SharedKey.username
}
private inline fun <reified T: Activity> launch():Boolean{
if(this is T) return closeDrawer()
val intent = Intent(applicationContext, T::class.java)
startActivity(intent)
finish()
return true
}
private fun closeDrawer(): Boolean {
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when (id) {
R.id.action_tasks -> {
return launch<TasksActivity>()
}
R.id.action_contacts -> {
return launch<ContactActivity>()
}
R.id.action_logout -> {
createExitDialog(loginService, this)
}
}
return false
}
}
抽屜的活動必須繼承這個BaseAppCompatActivity
,在設置內容后調用super.onCreate
(實際上,可以移動到一些 init 方法)並在其布局中具有對應的 id 元素
我的回答只是一個沒有任何源代碼的概念性回答。 對於一些像我這樣的讀者來說,理解它可能很有用。
這取決於您如何構建應用程序的初始方法。 基本上有兩種方法。
您創建一個活動(基本活動),所有其他視圖和屏幕都將是片段。 該基本活動包含抽屜和協調器布局的實現。 這實際上是我的首選方式,因為擁有小的獨立片段將使應用程序開發更容易、更順暢。
如果您已經開始使用活動開發應用程序,每個屏幕一個,那么您可能會創建基礎活動,所有其他活動都從它擴展。 基本活動將包含抽屜和協調器實現的代碼。 任何需要抽屜實現的活動都可以從基礎活動擴展。
我個人更願意避免在沒有任何組織的情況下混合使用片段和活動。 這會使開發變得更加困難,並最終讓您陷入困境。 如果你已經這樣做了,重構你的代碼。
在下面的視頻教程中詳細說明
制作基礎導航抽屜活動並將該基礎導航抽屜活動擴展到您想要顯示導航抽屜的所有活動非常容易,
所有步驟都在視頻中清楚地解釋了
使用片段在您的 MainActivity 中創建導航抽屜。
在 MainActivity 中初始化 Navigation Drawer
現在在所有其他想要使用相同導航抽屜的活動中,將 DrawerLayout 作為基礎並將片段作為導航抽屜。 只需在您的片段中設置 android:name 指向您的片段 Java 文件。 您不需要在其他活動中初始化片段。
您可以通過在 Google Play 商店應用等其他活動中滑動來訪問 Nav Drawer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.