Android编程使用Fragment界面向下跳转并一级级返回的实现方法

 更新时间:2015年10月30日 14:47:42   作者:_YMW  
这篇文章主要介绍了Android编程使用Fragment界面向下跳转并一级级返回的实现方法,较为详细的分析了Fragment界面跳转所涉及的相关知识点与实现技巧,并附带了完整的实例代码供读者下载参考,需要的朋友可以参考下

本文实例讲述了Android编程使用Fragment界面向下跳转并一级级返回的实现方法。分享给大家供大家参考,具体如下:

1.首先贴上项目结构图:

2.先添加一个接口文件BackHandledInterface.java,定义一个setSelectedFragment方法用于设置当前加载的Fragment在栈顶,主界面MainActivity须实现此接口,代码如下:

package com.example.testdemo;
public interface BackHandledInterface {
  public abstract void setSelectedFragment(BackHandledFragment selectedFragment);
}

3.定义一个抽象类BackHandledFragment继承自Fragment,后面跳转的Fragment界面都要继承自BackHandledFragment。抽象类BackHandledFragment中定义一个返回值为boolean类型的onBackPressed方法,用于处理点击返回按键(物理Back键)时的逻辑,若该方法返回false,表示当前Fragment不消费返回事件,而由Fragment所属的FragmentActivity来处理这个事件。代码如下:

package com.example.testdemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public abstract class BackHandledFragment extends Fragment {
  protected BackHandledInterface mBackHandledInterface;
  /**
   * 所有继承BackHandledFragment的子类都将在这个方法中实现物理Back键按下后的逻辑
   */
  protected abstract boolean onBackPressed();
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (!(getActivity() instanceof BackHandledInterface)) {
      throw new ClassCastException(
          "Hosting Activity must implement BackHandledInterface");
    } else {
      this.mBackHandledInterface = (BackHandledInterface) getActivity();
    }
  }
  @Override
  public void onStart() {
    super.onStart();
    // 告诉FragmentActivity,当前Fragment在栈顶
    mBackHandledInterface.setSelectedFragment(this);
  }
}

4.主界面MainActivity要继承FragmentActivity才能调用getSupportFragmentManager()方法来处理Fragment。MainActivity还需重写onBackPressed方法用来捕捉返回键(Back Key)事件,代码如下:

package com.example.testdemo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity implements
    BackHandledInterface {
  private static MainActivity mInstance;
  private BackHandledFragment mBackHandedFragment;
  private Button btnSecond;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnSecond = (Button) findViewById(R.id.btnSecond);
    btnSecond.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        FirstFragment first = new FirstFragment();
        loadFragment(first);
        btnSecond.setVisibility(View.GONE);
      }
    });
  }
  public static MainActivity getInstance() {
    if (mInstance == null) {
      mInstance = new MainActivity();
    }
    return mInstance;
  }
  public void loadFragment(BackHandledFragment fragment) {
    BackHandledFragment second = fragment;
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.firstFragment, second, "other");
    ft.addToBackStack("tag");
    ft.commit();
  }
  @Override
  public void setSelectedFragment(BackHandledFragment selectedFragment) {
    this.mBackHandedFragment = selectedFragment;
  }
  @Override
  public void onBackPressed() {
    if (mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()) {
      if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        super.onBackPressed();
      } else {
        if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
          btnSecond.setVisibility(View.VISIBLE);
        }
        getSupportFragmentManager().popBackStack();
      }
    }
  }
}

5.分别添加两个子级Fragment,FirstFragment.java和SecondFragment.java,代码分别如下:

FirstFragment.java:

package com.example.testdemo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class FirstFragment extends BackHandledFragment {
  private View myView;
  private Button btnSecond;
  @Override
  public View onCreateView(LayoutInflater inflater,
      @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    myView = inflater.inflate(R.layout.fragment_first, null);
    initView();
    return myView;
  }
  private void initView() {
    btnSecond = (Button) myView.findViewById(R.id.btnSecond);
    btnSecond.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        SecondFragment second = new SecondFragment();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.firstFragment, second);
        ft.addToBackStack("tag");
        ft.commit();
      }
    });
  }
  @Override
  protected boolean onBackPressed() {
    return false;
  }
}

SecondFragment.java:

package com.example.testdemo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SecondFragment extends BackHandledFragment {
  private View mView;
  @Override
  public View onCreateView(LayoutInflater inflater,
      @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_second, null);
    return mView;
  }
  @Override
  protected boolean onBackPressed() {
    return false;
  }
}

6.三个布局文件代码如下:

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="FragmentActivity 父界面"
    android:textSize="26sp" />
  <Button
    android:id="@+id/btnSecond"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="跳转到FirstFragment" />
  <FrameLayout
    android:id="@+id/firstFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
  </FrameLayout>
</RelativeLayout>

fragment_first.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"
  android:background="#e5e5e5"
  android:orientation="vertical" >
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="FirstFragment"
    android:textColor="#000000"
    android:textSize="26sp" />
  <Button
    android:id="@+id/btnSecond"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="打开SecondFragment" />
</RelativeLayout>

fragment_second.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"
  android:background="#e5e5e5"
  android:orientation="vertical" >
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="SecondFragment"
    android:textColor="#000000"
    android:textSize="26sp" />
</RelativeLayout>

7.最后奉上实例链接:

完整实例代码代码点击此处本站下载

希望本文所述对大家Android程序设计有所帮助。

相关文章

  • 利用Fiddler对手机进行抓包的实现方法

    利用Fiddler对手机进行抓包的实现方法

    下面小编就为大家带来一篇利用Fiddler对手机进行抓包的实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • Android自带的四种线程池使用总结

    Android自带的四种线程池使用总结

    本篇文章主要介绍了Android自带的四种线程池使用总结,详细的介绍了4种线程池的用法,具有一定的参考价值,有兴趣的小伙伴可以了解一下
    2017-07-07
  • Android编程之SDK安装组件的离线安装方法分享

    Android编程之SDK安装组件的离线安装方法分享

    这篇文章主要介绍了Android编程之SDK安装组件的离线安装方法,提供了离线sdk的下载地址与下载方法,以及离线安装的具体操作步骤,需要的朋友可以参考下
    2015-12-12
  • android命令行模拟输入事件(文字、按键、触摸等)

    android命令行模拟输入事件(文字、按键、触摸等)

    这篇文章主要给大家介绍了关于android命令行模拟输入事件,例如文字、按键、触摸等的相关资料,文中通过示例代码介绍的非常详细,对各位android开发者们具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-06-06
  • Android开发环境搭建图文教程 亲测有效!

    Android开发环境搭建图文教程 亲测有效!

    这篇文章主要为大家详细介绍了Android开发环境搭建图文教程,亲自测试有效的搭建方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-03-03
  • Android Listview点赞问题关于图片重复问题

    Android Listview点赞问题关于图片重复问题

    最近在开发android方面的项目时,遇到很多问题,下面小编以listview 与 baseadapter结合使用为例,给大家分享下关于点赞的的时候 图片重复问题的解决方法,一起看看吧
    2016-11-11
  • Android编程自定义AlertDialog样式的方法详解

    Android编程自定义AlertDialog样式的方法详解

    这篇文章主要介绍了Android编程自定义AlertDialog样式的方法,结合实例形式详细分析了Android自定义AlertDialog样式的具体布局与功能实现相关操作技巧,需要的朋友可以参考下
    2018-02-02
  • Kotlin 与 Jetpack Compose 参数设计完全指南(最新推荐)

    Kotlin 与 Jetpack Compose 参数设计完全指南(最新推荐)

    作为 Kotlin 和 Jetpack Compose 开发者,合理的参数设计能显著提升代码的可读性和易用性,本文将系统整理各类参数规则,帮助您编写更优雅的 API,感兴趣的朋友一起看看吧
    2025-04-04
  • 简单谈谈我的Android屏幕适配之路

    简单谈谈我的Android屏幕适配之路

    我相信Android碎片化问题是让所有的Android开发者都比较头疼的问题.尤其是屏幕适配这一块儿.想要自己的app在不同的设备上面都有一个比较好的显示效果.就必须做好相应的屏幕适配.
    2017-11-11
  • ViewPager+PagerAdapter实现带指示器的引导页

    ViewPager+PagerAdapter实现带指示器的引导页

    这篇文章主要为大家详细介绍了ViewPager+PagerAdapter实现带指示器的引导页,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-09-09

最新评论