Android 는 아래쪽 탐색 표시 줄 의 메 인 화면 을 구현 합 니 다.

주류 app 에서 응 용 된 메 인 화면 은 모두 아래쪽 에 여러 개의 탭 이 있 는 네 비게 이 션 표시 줄 입 니 다.클릭 하면 해당 하 는 화면 으로 전환 할 수 있 습 니 다.그림 과 같 습 니 다.

다음은 그 실현 과정 을 묘사 할 것 이다.
1.먼저 분석 인터페이스 입 니 다.밑 에 있 는 네 비게 이 션 표시 줄 은 화면 너 비 를 차지 하고 여러 개의 태그 TextView 를 감 싸 며 방향 은 가로 horizontal 의 선형 레이아웃 LinearLayout 입 니 다.위쪽 은 남 은 공간 을 차지 하 는 FrameLayout 입 니 다.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity"
 android:orientation="vertical">
 <FrameLayout
 android:id="@+id/main_layout"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_weight="1"/>
 <View
 android:layout_width="match_parent"
 android:layout_height="1px"
 android:background="@color/colorPrimaryDark"
 />
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal">
 <TextView
 android:id="@+id/main_home"
 android:layout_width="wrap_content"
 android:layout_weight="1"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:padding="20dp"
 android:text="  "
 />
 <View
 android:layout_width="1px"
 android:layout_height="match_parent"
 android:background="@color/colorPrimaryDark"
 />
 <TextView
 android:id="@+id/main_game"
 android:layout_width="wrap_content"
 android:layout_weight="1"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:padding="20dp"
 android:text="  "
 />
 <View
 android:layout_width="1px"
 android:layout_height="match_parent"
 android:background="@color/colorPrimaryDark"
 />
 <TextView
 android:id="@+id/main_video"
 android:layout_width="wrap_content"
 android:layout_weight="1"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:padding="20dp"
 android:text="  "
 />
 <View
 android:layout_width="1px"
 android:layout_height="match_parent"
 android:background="@color/colorPrimaryDark"
 />
 <TextView
 android:id="@+id/main_mine"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:gravity="center"
 android:padding="20dp"
 android:text="  "
 />
 </LinearLayout>
</LinearLayout>
2.네 개의 탭 은 네 개의 Fragment 에 대응 합 니 다.우 리 는 네 개의 Fragment 를 새로 만 들 고 구 조 는 TextView 를 놓 아 구분 하면 됩 니 다.

private HomeFragment homeFragment;
private GameFragment gameFragment;
private VideoFragment videoFragment;
private MineFragment mineFragment;
3.MainActivity 를 열 고 컨트롤 을 초기 화 합 니 다.

private void initView() {
 home= findViewById(R.id.main_home);
 game= findViewById(R.id.main_game);
 video= findViewById(R.id.main_video);
 mine= findViewById(R.id.main_mine);
 layout= findViewById(R.id.main_layout);
 
 home.setOnClickListener(this);
 game.setOnClickListener(this);
 video.setOnClickListener(this);
 mine.setOnClickListener(this);
}
onClick 클릭 이벤트 뒤로 처리
3.프 래 그 먼 트 4 개 초기 화
프 래 그 먼 트 를 한 번 불 러 온 후에 반복 적 으로 클릭 하거나 전환 하면 자원 을 소모 하지 않 습 니 다.여기 서 흔히 볼 수 있 는 처리 방식 은 view pager 의 게 으 른 로드 와 fragment 의 hide,show 가 있 습 니 다.여기 서 후자 의 실현 방식 을 설명 합 니 다.

private void initFragment() {
 FragmentTransaction transaction= getSupportFragmentManager().beginTransaction();
 if (homeFragment!= null&& homeFragment.isAdded()){
 transaction.remove(homeFragment);
 }
 if (gameFragment!= null&& gameFragment.isAdded()){
 transaction.remove(gameFragment);
 }
 if (videoFragment!= null&& videoFragment.isAdded()){
 transaction.remove(videoFragment);
 }
 if (mineFragment!= null&& mineFragment.isAdded()){
 transaction.remove(mineFragment);
 }
 transaction.commitAllowingStateLoss();
 homeFragment= null;
 gameFragment= null;
 videoFragment= null;
 mineFragment= null;
 home.performClick();
}
코드 를 한 줄 씩 분석 해 보도 록 하 겠 습 니 다.
우선 트 랜 잭 션 을 시작 합 니 다.

FragmentTransaction transaction= getSupportFragmentManager().beginTransaction();
Fragment 의 비공 식 처 리 를 진행 합 니 다.

if (homeFragment!= null&& homeFragment.isAdded()){
 transaction.remove(homeFragment);
}
if (gameFragment!= null&& gameFragment.isAdded()){
 transaction.remove(gameFragment);
}
if (videoFragment!= null&& videoFragment.isAdded()){
 transaction.remove(videoFragment);
}
if (mineFragment!= null&& mineFragment.isAdded()){
 transaction.remove(mineFragment);
}
transaction.commitAllowingStateLoss();
모든 fragment 를 null 로 설정 하고 홈 fragment 의 클릭 이 벤트 를 자동 으로 실행 합 니 다.즉,홈 Fragment 를 기본 값 으로 표시 합 니 다.

homeFragment= null;
gameFragment= null;
videoFragment= null;
mineFragment= null;
home.performClick();
4.네 개의 아래쪽 탭 의 클릭 이벤트 로 돌아 가 사용자 정의 switchContent 방법 을 실행 하고 현재 탭 을 클릭 한 view 를 매개 변수 로 전송 합 니 다.

@Override
public void onClick(View view) {
 switch (view.getId()){
 case R.id.main_home:
 switchContent(home);
 break;
 case R.id.main_game:
 switchContent(game);
 break;
 case R.id.main_video:
 switchContent(video);
 break;
 case R.id.main_mine:
 switchContent(mine);
 break;
 }
}
5.switch Content 로 위 치 를 정 하 는 방법
새 fragment 대상 을 만 듭 니 다.탭 을 클릭 할 때 현재 fragment 대상 이 비어 있 으 면 fragment 에 대응 하 는 대상 인 스 턴 스 를 생 성 합 니 다.

public void switchContent(View view){
 Fragment fragment;
 if (view== home){
 if (homeFragment== null){
 homeFragment= new HomeFragment();
 }
 fragment= homeFragment;
 }else if (view== game){
 if (gameFragment== null){
 gameFragment= new GameFragment();
 }
 fragment= gameFragment;
 }else if (view== video){
 if (videoFragment== null){
 videoFragment= new VideoFragment();
 }
 fragment= videoFragment;
 }else if (view== mine){
 if (mineFragment== null){
 mineFragment= new MineFragment();
 }
 fragment= mineFragment;
 }else {
 return;
 }
대상 을 만 든 후에 우 리 는 fragment 의 추가 디 스 플레이 작업 을 할 수 있 습 니 다.

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (mContent == null) {
 transaction.add(layout.getId(), fragment).commit();
 mContent = fragment;
}
if (mContent != fragment) {
 if (!fragment.isAdded()) {
 transaction.hide(mContent).add(layout.getId(), fragment).commitAllowingStateLoss();
 } else {
 transaction.hide(mContent).show(fragment).commitAllowingStateLoss();
 }
 mContent = fragment;
}
home.setSelected(false);
home.setSelected(false);
home.setSelected(false);
home.setSelected(false);
view.setSelected(true);
이 코드 를 분석 하면 우 리 는 주로 현재 조각 mContent 와 이전 조각 fragment 를 비교 합 니 다.이렇게 하면 아래쪽 네 비게 이 션 표시 줄 이 클릭 하여 전환 되 었 는 지 판단 할 수 있 습 니 다.먼저 응용 프로그램 이 열 렸 을 때 우리 앞 에 첫 번 째 탭 자동 클릭 방법 을 호출 했 기 때 문 입 니 다.

home.performClick();
절 차 를 보 세 요.이때 mContent 는 null 이기 때문에 이 코드 를 사용 합 니 다.

if (mContent == null) {
 transaction.add(layout.getId(), fragment).commit();
 mContent = fragment;
}
이 때 fragment 는 HomeFragment 대상 이 며 페이지 는 HomeFragment 를 표시 하고 이 대상 을 mContent 에 부여 합 니 다.
이때 HomeFragment 의 생명 주 기 는 다음 과 같 습 니 다.Attach()에서 onResume()까지 모든 것 이 정상 입 니 다.

다음은 두 번 째 탭 을 클릭 하 십시오.fragment 는 gameFragment 이 고 mContent 는 homeFragment 입 니 다.양 자 는 같 지 않 으 니 이 방법 으로 가자.

if (mContent != fragment) {
 if (!fragment.isAdded()) {
 transaction.hide(mContent).add(layout.getId(), fragment).commitAllowingStateLoss();
 } else {
 transaction.hide(mContent).show(fragment).commitAllowingStateLoss();
 }
 mContent = fragment;
}
분석 코드,GameFragment 는 아직 불 러 오지 않 았 기 때문에 먼저 갑 니 다.

transaction.hide(mContent).add(layout.getId(), fragment).commitAllowingStateLoss();
mContent 즉 HomeFragment 를 숨 기 고 GameFragment 를 불 러 와 표시 하 는 것 입 니 다.
이때 GameFragment 의 생명 주 기 를 보면 모든 것 이 정상 입 니 다.

이때 우 리 는 HomeFragment 를 다시 클릭 합 니 다.이때 fragment 는 HomeFragment 이 고 mContent 는 GameFragment 입 니 다.그리고 HomeFragment 는 add 되 었 기 때문에 갑 니 다.

transaction.hide(mContent).show(fragment).commitAllowingStateLoss();
이 문 구 는 fragment 를 숨 기 는 동시에 add 가 불 러 온 fragment 를 불 러 오지 않 아 도 됩 니 다.직접 show 하면 됩 니 다.commt Allowing StateLoss 방법 은 commt 방법 과 유사 합 니 다.이러한 잦 은 전환 페이지 에서 제출 하 는 작업 을 사용 하여 crash 를 피 할 수 있 습 니 다.
동시에 로 그 를 열 어 보 니 HomeFragment 가 삭제 되 지 않 고 다시 불 러 오지 않 았 습 니 다.그러면 자주 불 러 오 는 것 을 전환 하고 싶 지 않 은 목적 을 달성 할 수 있 습 니 다. 
이로써 모두 완성,데모 첨부!
자원 다운로드
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기