我已经创建了一个底部导航,但是当我在底部导航中选择选项时,该片段不会用另一个替换。 这是我的代码。 任何帮助将不胜感激。 这是我在android studio项目中编写的代码,我不知道为什么它不加载片段。
主要活动
package com.divesh.ss;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new dash());
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setSelectedItemId(R.id.dashboard);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.settings:
fragment = new settings();
loadFragment(fragment);
return true;
case R.id.work:
fragment = new work();
loadFragment(fragment);
return true;
case R.id.donate:
fragment = new donate();
loadFragment(fragment);
return true;
case R.id.team:
fragment = new team();
loadFragment(fragment);
return true;
}
return false;
}
};
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.divesh.ss.MainActivity">
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:itemBackground="@color/colorPrimary"
android:foreground="?attr/selectableItemBackground"
app:itemIconTint="@android:color/white"
app:itemTextColor="@android:color/white"
app:menu="@menu/navigation" />
</android.support.design.widget.CoordinatorLayout>
答案 0 :(得分:2)
您为BottomView导航创建了侦听器,但未设置它。
您需要为导航设置监听器:
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);