繁体   English   中英

如何使用 Android Jetpack 导航组件导航到菜单项单击的片段

[英]How to navigate to a Fragment on menu item click using Android Jetpack Navigation component

如何在单击菜单项时导航到片段。 使用 android 导航组件。谢谢

我假设您使用的是kotlinOne Activity模式,请执行以下步骤

构建.gradle

implementation "androidx.navigation:navigation-fragment-ktx:2.3.0-alpha03"
implementation "androidx.navigation:navigation-ui-ktx:2.3.0-alpha03"

在 res-> menu 文件夹中添加菜单

main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/fragment_two"
    android:title="Fragment Two"
    />
</menu>

主要活动

class MainActivity : AppCompatActivity() {
lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    navController = findNavController(this, R.id.nav_host_fragment)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.main_menu, menu)
    return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item)
}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<fragment
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/main_graph" />

</androidx.constraintlayout.widget.ConstraintLayout>

在 res->navigation mian_graph.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_graph"
app:startDestination="@id/fragment_one">

<fragment android:id="@+id/fragment_one"
    android:label="FragmentOne"
    android:name="com.mohammedalaamorsi.test.FragmentOne" />// here you should put the path for your fragment


<fragment android:id="@+id/fragment_two"
    android:label="FragmentTwo"
    android:name="com.mohammedalaamorsi.test.FragmentTwo" />// here you should put the path for your fragment

</navigation>

你可以试试这个

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
            inflater.inflate(R.menu.menu_home, menu)
            var item: MenuItem = menu.findItem(R.id.actionABC)
            item.actionView.findViewById<AppCompatImageView>(R.id.ivScheduledTrip).setOnClickListener {

            }
            item = menu.findItem(R.id.actionABC)
            item.actionView.findViewById<AppCompatImageView>(R.id.ivShareRide).setOnClickListener {

            }
            super.onCreateOptionsMenu(menu, inflater)
        }

你可以试试

public boolean onNavigationItemSelected(MenuItem item) {
    Fragment newFragment; // This is the fragment you want to put into the FrameLayout

    int id = item.getItemId();
    if (id == R.id.nav_camara) {
        newFragment = new CameraFragment();
    } else if (id == R.id.nav_gallery) {
        newFragment = new GalleryFragment();
    } else if (id == R.id.nav_slideshow) {
        // [...]
    }

    // Let's put the new fragment into the FrameLayout
    // If you use the support action bar, use getSupportFragmentManager(), else getFragmentManager()
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, newFragment); // R.id.fragment_container = FrameLayout ID
    transaction.commit();
} 

在科特林:

onNavigationItemSelected中,您会找到每个菜单项的when块。 when块中的内容替换为以下代码:

R.id.nav_inbox -> {
  navController.navigate(R.id.inboxFragment)  //1
}

R.id.nav_sent -> {
  navController.navigate(R.id.sentFragment)  //2
}

R.id.nav_privacy_policy -> {
  navController.navigate(//id)  //3
}

R.id.nav_terms_of_service -> {
  navController.navigate(//id)  //4
}

对于 java,请查看https://www.androidauthority.com/android-navigation-architecture-component-908660/ 我希望你能从那里得到更多的解释。

这是主要活动

public class MainActivity extends AppCompatActivity implements 
            BottomNavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );

    bottomNavigationView = findViewById( R.id.bottom_navigation_view );
    bottomNavigationView.setItemIconTintList( null );
    bottomNavigationView.setOnNavigationItemSelectedListener( this );
   navController = Navigation.findNavController(this, R.id.nav_host_container);
    NavigationUI.setupActionBarWithNavController(this, navController);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment fragment = null;
    switch (item.getItemId()) {
        case R.id.categoryFragment:
           Log.e("Click","categoryFragment");
            break;
        case R.id.favouriteFragment:
         Log.e("Click","favouriteFragment");
            break;
        case R.id.myPostFragment:
           Log.e("Click","myPostFragment");
            break;
    }
  return NavigationUI.onNavDestinationSelected(item, navController) || 
 super.onOptionsItemSelected(item);
}

}

activity_main.xml

 <LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
    android:id="@+id/nav_host_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="androidx.navigation.fragment.NavHostFragment"
    app:navGraph="@navigation/main"
    android:layout_marginBottom="56dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:defaultNavHost="true" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation_view"
    android:layout_width="0dp"
    android:layout_height="60dp"
    android:background="#fff"
    app:itemIconTint="@drawable/tab_color"
    app:itemTextColor="@drawable/tab_color"
    app:labelVisibilityMode="labeled"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:menu="@menu/bottom_nav_menu" />

现在在 res 文件夹中创建名为 navigation 的文件夹并将其命名为 main.xml

<navigation
android:id="@+id/main.xml"
app:startDestination="@id/categoryFragment">

<fragment
    android:id="@+id/categoryFragment"
    android:name="com.therock.fragmentbackpressdemo.CategoryFragment"
    android:label="Category Fragment">
</fragment>
<fragment
    android:id="@+id/favouriteFragment"
    android:name="com.therock.fragmentbackpressdemo.FavouriteFragment"
    android:label="Favourite Fragment">
</fragment>
<fragment
    android:id="@+id/myPostFragment"
    android:name="com.therock.fragmentbackpressdemo.MyPostFragment"
    android:label="MyPostFragment">
</fragment>
 After struggling hours found better way as below

 override fun onOptionsItemSelected(item: MenuItem): Boolean {
    // Handle item selection
    return when (item.getItemId()) {
        R.id.menu_cart -> {
           // log("$TAG", "menu_cart is clicked")                
       findNavController(R.id.nav_host_fragment_content_activity_dashborad)
           .navigate(R.id.nav_cartList)               
      //Navigation.findNavController(binding.root)
            //.navigate(R.id.nav_cartList);
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

// nav_host_fragment_content_activity_dashborad  is the NavHostFragment where app:navGraph="@navigation/mobile_navigation" is applied.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM