在BottomNavigationView中切换片段

时间:2017-06-08 00:54:42

标签: android android-fragments bottomnavigationview

我正在使用一个带有底部导航视图的简单应用程序。我有3个片段(布局和java)。我有一个BottonNavigationView,在我的MainActivity.java中声明。我的bottonnavigation有3个项目,3个片段。所以,在我的MainActivity.java中,当我选择一个项目时,它会启动一个片段。所以,当我再次选择另一个项目时,没有任何反应,因为在java片段中我需要声明BottonNavigationView,但我不知道如何设置它以用另一个片段切换实际片段。 我试过这个链接,但没有成功:https://developer.android.com/training/basics/fragments/fragment-ui.html

抱歉我的英文不好

这里是代码:

主要活动

 @Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment selectedFragment = null;
    switch (item.getItemId()) {
        case R.id.navigation_home:
            selectedFragment = HomeFragment.newInstance();
            break;
        case R.id.navigation_dashboard:
            selectedFragment = DashboardFragment.newInstance();
            break;
        case R.id.navigation_notifications:
            selectedFragment = NotificationsFragment.newInstance();
            break;
    }
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content, selectedFragment);
    transaction.commit();
    return true;
}

片段Java示例

public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.navigation_home, container, false);
return inflater.inflate(R.layout.navigation_home, container, false);
}

6 个答案:

答案 0 :(得分:5)

你可以尝试一下:

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment selectedFragment = null;
    switch (item.getItemId()) {
        case R.id.navigation_home:
            selectedFragment = HomeFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.content, selectedFragment).commit();
            break;
        case R.id.navigation_dashboard:
            selectedFragment = DashboardFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.content, selectedFragment).commit();
            break;
        case R.id.navigation_notifications:
            selectedFragment = NotificationsFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.content, selectedFragment).commit();
            break;
    }
    return true;
}

答案 1 :(得分:1)

在这种情况下,最好尝试从fragmentManager获取fragmentManager.findFragmentByTag(tag)中存在的片段。您可以更顺利地切换,并且您不需要例如从网络加载一些内容(如果您在片段或片段的演示者中有这样的代码)

答案 2 :(得分:1)

您不必每次都创建newInstance。您可以保存片段状态。请点击以下链接

fragmentManager.beginTransaction().hide(toBeHidden).show(toBeShown).commit();

https://medium.com/@oluwabukunmi.aluko/bottom-navigation-view-with-fragments-a074bfd08711

答案 3 :(得分:0)

您应该从每个片段创建一次newIstance。然后可以隐藏活动片段,然后显示新片段。

    Fragment activeFragment;
    ArrayList<Fragment> fragment;

public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;
            switch (item.getItemId()) {
                case R.id.navigation_fragment:
                    selectedFragment = ShowMyFragment.newInstance();
                    replaceFragment(selectedFragment);
                    return true;
}
});
    private void replaceFragment(Fragment selectedFragment) {
        boolean lastOpened = false;
        for ( int i=0; i<fragment.size();i++ )
        {
            if ( fragment.get(i) == selectedFragment ) {
                lastOpened = true;
                break;
            }
        }
        if (!lastOpened) {
            getSupportFragmentManager().beginTransaction().replace(R.id.content, selectedFragment).commit();
        }
        else
        {
            getSupportFragmentManager().beginTransaction().hide(activeFragment).show(selectedFragment).commit();
        }

        activeFragment = selectedFragment;
    }

答案 4 :(得分:0)

只需在onCreate中添加这样的空白实现 bottomNavView.setOnNavigationItemReselectedListener {}

答案 5 :(得分:0)

我的完整解决方案,对大三学生而言将是有用的:

所以,我们有MainActivity:

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class MainMenuActivity : AppCompatActivity() {

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

  val bottomNav: BottomNavigationView = findViewById(R.id.bottom_naviagtion)
  bottomNav.setOnNavigationItemSelectedListener(navListener)

    if (savedInstanceState == null) {
         supportFragmentManager.beginTransaction().replace(
              R.id.fragment_container,
             HomeFragment()
         ).commit()
     }
 }

 private val navListener: BottomNavigationView.OnNavigationItemSelectedListener =
      BottomNavigationView.OnNavigationItemSelectedListener { item ->
         var selectedFragment: Fragment? = null
         when (item.itemId) {
        R.id.bottom_home -> selectedFragment =
            HomeFragment()
        R.id.bottom_events -> selectedFragment =
            EventFragment()
        R.id.bottom_contacts -> selectedFragment =
            ContactsFragment()
        R.id.bottom_menu -> selectedFragment =
            MenuFragment()
    }
    supportFragmentManager.beginTransaction().replace(
        R.id.fragment_container,
        selectedFragment!!
     ).commit()
     true
 }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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">

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottom_naviagtion"/>

<View
    android:layout_width="match_parent"
    android:layout_height="10dp"
    android:layout_above="@id/bottom_naviagtion"
    android:background="@drawable/shadow"/>

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_naviagtion"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:menu="@menu/bottom_menu"
    android:background="?android:attr/windowBackground" />

</RelativeLayout>

每个片段类如下:

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class HomeFragment : Fragment() {
   override fun onCreateView(
       inflater: LayoutInflater,
       container: ViewGroup?,
       savedInstanceState: Bundle?
   ): View? {
       return inflater.inflate(R.layout.fragment_home, container, false)
   }
 }

.HomeFragment(fragment_home.xml)的.xml文件看起来像(其他片段看起来一样):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/home"
    android:textSize="30sp"
    android:layout_centerInParent="true"/>

</RelativeLayout>

NavigationBottomMenu .xml外观(bottom_menu.xml):

<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">

<item
    android:id="@+id/bottom_home"
    android:icon="@drawable/home_selector"
    android:title="Home" />


<item
    android:id="@+id/bottom_events"
    android:icon="@drawable/events_selector"
    android:title="Events" />

<item
    android:id="@+id/bottom_contacts"
    android:icon="@drawable/contacts_selector"
    android:title="Contacts"/>

<item
    android:id="@+id/bottom_menu"
    android:icon="@drawable/menu_selector"
    android:title="Menu" />

</menu>

从drawble文件夹中使用的图标已像Vector Asset一样导入