Implemente a barra de menu inferior primeiro
Esta parte refere-se ao vídeo da estação B Springboot:
2022 versão mais recente] O Android Studio instala o Android (Android) para desenvolver uma entrada baseada em zero para dominar o conjunto completo de tutoriais
Renderizações P118-119 :
- Esqueci se devo adicionar dependências. Há uma grande probabilidade de não haver necessidade de adicioná-las, mas mesmo assim posto primeiro as possíveis dependências.
implementation 'androidx.navigation:navigation-fragment:2.3.5'
implementation 'androidx.navigation:navigation-ui:2.3.5'
- Primeiro crie um arquivo de recurso (arquivo xml) de buttom_nav_menu no pacote de menu em res (se não houver pacote de menu) , o código é:
<?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>
- Em seguida, crie quatro arquivos de fragmentos correspondentes com base em HomeActivity
- Em seguida, o código em 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;
}
}
- O código no fragmento:
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;
}
}
O mesmo vale para outros fragmentos
alcançar o salto
Artigo de referência: Como o Android salta de uma atividade para um fragmento especificado em outra atividade
Descrição do problema: Ao concluir o design, é necessário retornar de activityA (ou seja, ActivityDetailActivity) para a interface antes de entrar (talvez fragmentA (ou seja, homeFragment) ou fragmentB (ou seja, mineFragment) quando o botão de retorno for clicado. Ambos pertencem a HomeActivity ).
Ideia: ao pular de ActivityDetailActivity, pule com um sinalizador e pule para o fragmento especificado de acordo com o sinalizador
O código para a parte ActivityDetailActivity:
Intent intent = new Intent();
intent.setClass(ActivityDetailActivity.this,HomeActivity.class);
intent.putExtra("fragment_flag",2);
startActivity(intent);
A parte HomeActivity só precisa fazer um julgamento sobre o valor retornado e alternar para o fragmento especificado de acordo com o valor. O código adicionado:
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();
Neste ponto, o código completo de 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;
}
}