从一个Activity跳转到另一个Activity的指定Fragment,附底部菜单栏的实现

先实现底部菜单栏

这部分参考B站视频Springboot:
2022最新版】Android Studio 安装 Android(安卓)开发零基础入门到精通全套教程P118-119
效果图:在这里插入图片描述

  • 忘了需不需要添加依赖了,大概率是本来就有不用添加,但还是把可能有关的依赖先贴上来
    implementation 'androidx.navigation:navigation-fragment:2.3.5'
    implementation 'androidx.navigation:navigation-ui:2.3.5'
  • 先在res下的menu包里(没有就建一个menu包)新建一个buttom_nav_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:title="@string/bottom_title_home"
        android:icon="@drawable/home"/>
    <item
        android:id="@+id/bottom_notice"
        android:title="@string/bottom_title_notice"
        android:icon="@drawable/notice"
    />
    <item
        android:id="@+id/bottom_mine"
        android:title="@string/bottom_title_mine"
        android:icon="@drawable/person"/>
    <item
        android:id="@+id/bottom_unfold"
        android:title="@string/bottom_title_unfold"
        android:icon="@drawable/more"
        />

</menu>
  • 然后在HomeActivity的基础上创建四个对应的fragment文件
  • 然后HomeActivity里的代码
package com.example.academymanageapp.ui;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.ClipData;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.MenuItem;

import com.example.academymanageapp.R;
import com.example.academymanageapp.ui.base.BaseActivity;
import com.example.academymanageapp.ui.home.HomeFragment;
import com.example.academymanageapp.ui.mine.MineFragment;
import com.example.academymanageapp.ui.notice.NoticeFragment;
import com.example.academymanageapp.ui.unfold.UnfoldFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class HomeActivity extends BaseActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    private Fragment[] fragments; //fragment数组,用来存储底部菜单栏用到的fragment
    private int lastFragmentIndex = 0;//切换前的fragment
    private int nextFragmentIndex;//切换后的fragment
    private int fragmentFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initViews() {

        //初始化fragments
        fragments = new Fragment[]{new HomeFragment(),new NoticeFragment(), new MineFragment(),new UnfoldFragment()};
        //注册一个监听,用来监听用户点击底部菜单里的哪一个fragment
        BottomNavigationView bottomNavigationView = find(R.id.main_bottom_navigation);
        
        //设置默认的
        getSupportFragmentManager().beginTransaction().add(R.id.main_frame,fragments[0]).commit();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    //获得用户点击的menuItem
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//        item.getItemId();//获得用户点击的部件的Id
        item.setChecked(true);//给点中的item设置checked
        switch (item.getItemId()){
            case R.id.bottom_home:
                switchFragment(0);
                break;
            case R.id.bottom_notice:
                switchFragment(1);
                break;
            case R.id.bottom_mine:
                switchFragment(2);
                break;
            case R.id.bottom_unfold:
                switchFragment(3);
                break;
        }
        return false;
    }

    //默认点击是home,所以要创建一个fragment的切换
    private void switchFragment(int to){
        if (lastFragmentIndex == to){ //如果切换前后一致则不切换
            return;
        }
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        //如果没有添加过,则添加对应的fragment
        if (!fragments[to].isAdded()){
            fragmentTransaction.add(R.id.main_frame,fragments[to]);
        }else {
            fragmentTransaction.show(fragments[to]);//否则就展示出来
        }
        //添加后将之前的隐藏
        fragmentTransaction.hide(fragments[lastFragmentIndex]).commitAllowingStateLoss();
        lastFragmentIndex = to;
    }

}
  • fragment里的代码:
package com.example.academymanageapp.ui.mine;

import android.view.View;
import androidx.core.content.ContextCompat;
import com.example.academymanageapp.R;
import com.example.academymanageapp.databinding.FragmentMineBinding;
import com.example.academymanageapp.ui.base.BaseFragment;

public class MineFragment extends BaseFragment {
    private FragmentMineBinding binding;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentMineBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        return root;
        }
        
    @Override
    protected void initViews() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }
}

其他fragment同理

实现跳转

参考文章:android 如何从activity跳转到另一个activity下指定的fragment

问题描述:在做毕设的时候,需要实现点击返回按钮时从activityA(即ActivityDetailActivity)返回到进入前的界面(可能是fragmentA(即homeFragment),也有可能是fragmentB(即mineFragment),两者都属于HomeActivity)。

思路:从ActivityDetailActivity跳转时,带flag跳转,根据flag跳转到指定的fragment

ActivityDetailActivity部分的代码:

 Intent intent = new Intent();
 intent.setClass(ActivityDetailActivity.this,HomeActivity.class);
 intent.putExtra("fragment_flag",2);
 startActivity(intent);

HomeActivity部分只需要对传回来的值进行一个判断,根据值switch到指定的fragment就好,添加的代码:

fragmentFlag = getIntent().getIntExtra("fragment_flag",0);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (fragmentFlag){
            case 0:
                switchFragment(0);
                //使对应的底部菜单栏的Item处于被点击的状态(即点击都更改颜色)
                bottomNavigationView.setSelectedItemId(R.id.bottom_home);
                //调用底部菜单栏函数,以实现根据点击底部菜单栏实现fragment的跳转
                bottomNavigationView.setOnNavigationItemSelectedListener(this);
                //记得加break,否则页面不会变化
                break;
            case 1:
                switchFragment(1);
                bottomNavigationView.setSelectedItemId(R.id.bottom_notice);
                bottomNavigationView.setOnNavigationItemSelectedListener(this);
                break;
            case 2:
                switchFragment(2);
                bottomNavigationView.setSelectedItemId(R.id.bottom_mine);
                bottomNavigationView.setOnNavigationItemSelectedListener(this);
                break;
            case 3:
                switchFragment(3);
                bottomNavigationView.setSelectedItemId(R.id.bottom_unfold);
                bottomNavigationView.setOnNavigationItemSelectedListener(this);
                break;
        }
        transaction.commit();

此时HomeActivity的完整代码是:

package com.example.academymanageapp.ui;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.ClipData;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.MenuItem;

import com.example.academymanageapp.R;
import com.example.academymanageapp.ui.base.BaseActivity;
import com.example.academymanageapp.ui.home.HomeFragment;
import com.example.academymanageapp.ui.mine.MineFragment;
import com.example.academymanageapp.ui.notice.NoticeFragment;
import com.example.academymanageapp.ui.unfold.UnfoldFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class HomeActivity extends BaseActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    private Fragment[] fragments; //fragment数组,用来存储底部菜单栏用到的fragment
    private int lastFragmentIndex = 0;//切换前的fragment
    private int nextFragmentIndex;//切换后的fragment
    private int fragmentFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initViews() {

        //初始化fragments
        fragments = new Fragment[]{new HomeFragment(),new NoticeFragment(), new MineFragment(),new UnfoldFragment()};
        //注册一个监听,用来监听用户点击底部菜单里的哪一个fragment
        BottomNavigationView bottomNavigationView = find(R.id.main_bottom_navigation);

        fragmentFlag = getIntent().getIntExtra("fragment_flag",0);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (fragmentFlag){
            case 0:
                switchFragment(0);
                //使对应的底部菜单栏的Item处于被点击的状态(即点击都更改颜色)
                bottomNavigationView.setSelectedItemId(R.id.bottom_home);
                //调用底部菜单栏函数,以实现根据点击底部菜单栏实现fragment的跳转
                bottomNavigationView.setOnNavigationItemSelectedListener(this);
                //记得加break,否则页面不会变化
                break;
            case 1:
                switchFragment(1);
                bottomNavigationView.setSelectedItemId(R.id.bottom_notice);
                bottomNavigationView.setOnNavigationItemSelectedListener(this);
                break;
            case 2:
                switchFragment(2);
                bottomNavigationView.setSelectedItemId(R.id.bottom_mine);
                bottomNavigationView.setOnNavigationItemSelectedListener(this);
                break;
            case 3:
                switchFragment(3);
                bottomNavigationView.setSelectedItemId(R.id.bottom_unfold);
                bottomNavigationView.setOnNavigationItemSelectedListener(this);
                break;
        }
        transaction.commit();

        //设置默认的
        getSupportFragmentManager().beginTransaction().add(R.id.main_frame,fragments[0]).commit();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    //获得用户点击的menuItem
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//        item.getItemId();//获得用户点击的部件的Id
        item.setChecked(true);//给点中的item设置checked
        switch (item.getItemId()){
            case R.id.bottom_home:
                switchFragment(0);
                break;
            case R.id.bottom_notice:
                switchFragment(1);
                break;
            case R.id.bottom_mine:
                switchFragment(2);
                break;
            case R.id.bottom_unfold:
                switchFragment(3);
                break;
        }
        return false;
    }

    //默认点击是home,所以要创建一个fragment的切换
    private void switchFragment(int to){
        if (lastFragmentIndex == to){ //如果切换前后一致则不切换
            return;
        }
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        //如果没有添加过,则添加对应的fragment
        if (!fragments[to].isAdded()){
            fragmentTransaction.add(R.id.main_frame,fragments[to]);
        }else {
            fragmentTransaction.show(fragments[to]);//否则就展示出来
        }
        //添加后将之前的隐藏
        fragmentTransaction.hide(fragments[lastFragmentIndex]).commitAllowingStateLoss();
        lastFragmentIndex = to;
    }

}

猜你喜欢

转载自blog.csdn.net/zzzzzwbetter/article/details/129270964