Навигационный ящик заменяет фрагмент другим проблематичным сохранением опции ящика - PullRequest
0 голосов
/ 30 января 2020

У меня есть приложение c, содержащее макет ящика. Каждая опция в ящике открывает новую страницу фрагмента для просмотра пользователем. Вот код компоновки ящика.

<androidx.drawerlayout.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" />

    <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_main"
        app:menu="@menu/activity_main_drawer" />

</androidx.drawerlayout.widget.DrawerLayout>

Вот код app_bar_main. xml.

<androidx.coordinatorlayout.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=".DashBoardActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.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" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

А вот content_main. xml. А также основной вид деятельности DashBoardActivity.kt

class DashBoardActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)

        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        val navView: NavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.nav_company_emissions, R.id.nav_your_emissions, R.id.nav_contact,
                R.id.nav_privacy_policy
            ), drawerLayout
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
}

Насколько я понимаю, когда вы нажимаете кнопку в макете ящика, фрагмент во фрагменте хоста заменяется соответствующим нажатием на фрагмент.

Мои вопросы ... Как программно поместить другой фрагмент в это представление хоста навигации, который не был настроен с макетом ящика. Моя проблема в том, что один из фрагментов содержит профиль для пользователя с кнопкой редактирования. Я хочу открыть новый фрагмент, когда нажата кнопка редактирования, и пользователь sh не может получить доступ к ящику, когда он делает это, поэтому он не хочет go к другому действию.

Я просто хочу заменить profile_fragment на edit_fragment. Но когда я попробовал что-то подобное ниже, он поместил фрагмент на профиль, так что у вас получился странно выглядящий экран с двумя фрагментами друг над другом.

val frag: Fragment = EditYourEmissionsFragment()
val fragMan:FragmentManager = activity!!.supportFragmentManager
val fragTran: FragmentTransaction = fragMan.beginTransaction()
fragTran.add(R.id.nav_host_fragment, frag)
fragTran.addToBackStack(null)
fragTran.commit()

Я все еще относительный новичок, когда дело доходит до Android и Kotlin, поэтому я изо всех сил пытаюсь понять, как я бы go сделал в моем случае пользователя.

Сценарий, помогающий нарисовать картину того, что я хочу, чтобы произошло :

  1. Пользователь загружает приложение и попадает на home_fragment.
  2. Открывает меню ящика, щелкает profile_fragment.
  3. Как только в profile_fragment открывается, пользователь нажимает кнопку edit.
  4. Новый фрагмент занимает экран, но сохраняет возможность открывать ящик меню.
  5. Теперь пользователь может либо открыть меню ящика и перейти в другие места в приложении. Или сохраните их профиль и вернитесь в раздел profile_fragment.

Заранее благодарю за любую помощь. Извинения, если это не особенно ясно.

1 Ответ

2 голосов
/ 30 января 2020

включите EditYourEmissionsFragment в навигационный граф следующим образом:

    <fragment
        android:id="@+id/EditYourEmissionsFragment"
        android:name="com.example.application.EditYourEmissionsFragment"
        android:label="Edit Profile"
        tools:layout="@layout/fragment_edit_omissions"/>

, а затем в своем ProfileFragment установите onClick, чтобы открыть пункт назначения следующим образом;

        val navController = Navigation.findNavController(view)
        navController.navigate(R.id.EditYourEmissionsFragment)
...