Есть ли способ заставить NavigationView брать меньше кода (Kotlin) - PullRequest
0 голосов
/ 23 января 2020

Меня несколько считают (Kotlin новичок) и в настоящее время работают над задачей, а мой NavDrawer занимает слишком много места на каждой странице. У меня есть свои собственные Header content и Menu Items, но если я хочу включить их в каждую страницу, это займет слишком много места, и мне придется обновлять каждый drawer контент каждый раз, когда я редактирую, это будет очень много времени! Можно ли как-нибудь создать одно место, где хранится весь мой код NavDarwer, а затем просто включить его в другие страницы? Спасибо за чтение и ценим любые предложения

Редактировать-

Навигационный код:

<com.google.android.material.navigation.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"
        app:itemIconTint="@color/colorPrimary"
        app:menu="@menu/nav_menu" />

Код в MainActivity для навигации:

override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_latestAds -> {
                Toast.makeText(this, "You are currently here", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_cars -> {
                Toast.makeText(this, "Messages clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_properties -> {
                Toast.makeText(this, "Friends clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_mobiles -> {
                Toast.makeText(this, "Update clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_electDev -> {
                Toast.makeText(this, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_furniture -> {
                Toast.makeText(this, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_customerReg -> {
                Toast.makeText(this, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_vendorReg -> {
                val intent = Intent(this, RegisterVendor::class.java)
                startActivity(intent)
            }
            R.id.nav_logout -> {
                if (AuthService.isLoggedIn) {
                    UserDataService.logout()
                    Menu_userName.text = "User name"
                } else {
                    val loginIntent = Intent(this, Login::class.java)
                    startActivity(loginIntent)
                }
            }
        }
        drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }

Проблема в том, что если я хочу добавить NavigationView на каждую страницу, это займет много места в коде. Поэтому мне интересно, можно ли каким-либо образом создать ярлык, чтобы разместить весь код навигации в одном месте и передать его на другие страницы.

Последнее редактирование -

package com.example.wasit

import android.content.Context
import android.content.Intent
import android.view.MenuItem
import android.widget.Toast
import androidx.core.content.ContextCompat.startActivity
import com.example.wasit.Model.Login
import com.example.wasit.Model.RegisterVendor
import com.example.wasit.Services.AuthService
import com.example.wasit.Services.UserDataService

class NavigationHandler (val context: Context,val menuItem: MenuItem){
    operator fun invoke() {
        when (item.itemId) {
            R.id.nav_latestAds -> {
                Toast.makeText(context, "You are currently here", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_cars -> {
                Toast.makeText(context, "Messages clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_properties -> {
                Toast.makeText(context, "Friends clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_mobiles -> {
                Toast.makeText(context, "Update clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_electDev -> {
                Toast.makeText(context, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_furniture -> {
                Toast.makeText(context, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_customerReg -> {
                Toast.makeText(context, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_vendorReg -> {
                val intent = Intent(context, RegisterVendor::class.java)
                startActivity(intent)
            }
            R.id.nav_logout -> {
                if (AuthService.isLoggedIn) {
                    UserDataService.logout()
                    Menu_userName.text = "User name"
                } else {
                    val loginIntent = Intent(context, Login::class.java)
                    startActivity(loginIntent)
                }
            }
        }
    }
}

1 Ответ

0 голосов
/ 23 января 2020

Переместите код в другой класс и просто передайте необходимые ему зависимости:

class NavigationHandler(val context: Context, val menuItem: MenuItem){
    operator fun invoke() {
        when (item.itemId) {
            R.id.nav_latestAds -> {
                Toast.makeText(this, "You are currently here", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_cars -> {
                Toast.makeText(this, "Messages clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_properties -> {
                Toast.makeText(this, "Friends clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_mobiles -> {
                Toast.makeText(this, "Update clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_electDev -> {
                Toast.makeText(this, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_furniture -> {
                Toast.makeText(this, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_customerReg -> {
                Toast.makeText(this, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_vendorReg -> {
                val intent = Intent(this, RegisterVendor::class.java)
                startActivity(intent)
            }
            R.id.nav_logout -> {
                if (AuthService.isLoggedIn) {
                    UserDataService.logout()
                    Menu_userName.text = "User name"
                } else {
                    val loginIntent = Intent(this, Login::class.java)
                    startActivity(loginIntent)
                }
            }
        }
    }
}

И назовите его так:

override fun onNavigationItemSelected(item: MenuItem): Boolean {
    NavigationHandler(context, item)()
    drawerLayout.closeDrawer(GravityCompat.START)
    return true
}
...