Android 使用Fragment界面向下跳转并一级级返回

简介:

http://www.cnblogs.com/_ymw/p/4227862.html

 

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来处理这个事件。代码如下:

复制代码
复制代码
 1 package com.example.testdemo;
 2 
 3 import android.os.Bundle;
 4 import android.support.v4.app.Fragment;
 5 
 6 public abstract class BackHandledFragment extends Fragment {
 7 
 8     protected BackHandledInterface mBackHandledInterface;
 9 
10     /**
11      * 所有继承BackHandledFragment的子类都将在这个方法中实现物理Back键按下后的逻辑
12      */
13     protected abstract boolean onBackPressed();
14 
15     @Override
16     public void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         if (!(getActivity() instanceof BackHandledInterface)) {
19             throw new ClassCastException(
20                     "Hosting Activity must implement BackHandledInterface");
21         } else {
22             this.mBackHandledInterface = (BackHandledInterface) getActivity();
23         }
24     }
25 
26     @Override
27     public void onStart() {
28         super.onStart();
29         // 告诉FragmentActivity,当前Fragment在栈顶
30         mBackHandledInterface.setSelectedFragment(this);
31     }
32 
33 }
复制代码
复制代码

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

复制代码
复制代码
 1 package com.example.testdemo;
 2 
 3 import android.os.Bundle;
 4 import android.support.v4.app.FragmentActivity;
 5 import android.support.v4.app.FragmentManager;
 6 import android.support.v4.app.FragmentTransaction;
 7 import android.view.View;
 8 import android.view.View.OnClickListener;
 9 import android.widget.Button;
10 
11 public class MainActivity extends FragmentActivity implements
12         BackHandledInterface {
13     private static MainActivity mInstance;
14     private BackHandledFragment mBackHandedFragment;
15     private Button btnSecond;
16 
17     @Override
18     public void onCreate(Bundle savedInstanceState) {
19         super.onCreate(savedInstanceState);
20         setContentView(R.layout.activity_main);
21         btnSecond = (Button) findViewById(R.id.btnSecond);
22         btnSecond.setOnClickListener(new OnClickListener() {
23 
24             @Override
25             public void onClick(View v) {
26                 FirstFragment first = new FirstFragment();
27                 loadFragment(first);
28                 btnSecond.setVisibility(View.GONE);
29             }
30         });
31 
32     }
33 
34     public static MainActivity getInstance() {
35         if (mInstance == null) {
36             mInstance = new MainActivity();
37         }
38         return mInstance;
39     }
40 
41     public void loadFragment(BackHandledFragment fragment) {
42         BackHandledFragment second = fragment;
43         FragmentManager fm = getSupportFragmentManager();
44         FragmentTransaction ft = fm.beginTransaction();
45         ft.replace(R.id.firstFragment, second, "other");
46         ft.addToBackStack("tag");
47         ft.commit();
48     }
49 
50     @Override
51     public void setSelectedFragment(BackHandledFragment selectedFragment) {
52         this.mBackHandedFragment = selectedFragment;
53     }
54 
55     @Override
56     public void onBackPressed() {
57         if (mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()) {
58             if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
59                 super.onBackPressed();
60             } else {
61                 if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
62                     btnSecond.setVisibility(View.VISIBLE);
63                 }
64                 getSupportFragmentManager().popBackStack();
65             }
66         }
67     }
68 }
复制代码
复制代码

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

FirstFragment.java

复制代码
复制代码
 1 package com.example.testdemo;
 2 
 3 import android.os.Bundle;
 4 import android.support.annotation.Nullable;
 5 import android.support.v4.app.FragmentManager;
 6 import android.support.v4.app.FragmentTransaction;
 7 import android.view.LayoutInflater;
 8 import android.view.View;
 9 import android.view.View.OnClickListener;
10 import android.view.ViewGroup;
11 import android.widget.Button;
12 
13 public class FirstFragment extends BackHandledFragment {
14     private View myView;
15     private Button btnSecond;
16 
17     @Override
18     public View onCreateView(LayoutInflater inflater,
19             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
20         myView = inflater.inflate(R.layout.fragment_first, null);
21         initView();
22         return myView;
23     }
24 
25     private void initView() {
26         btnSecond = (Button) myView.findViewById(R.id.btnSecond);
27         btnSecond.setOnClickListener(new OnClickListener() {
28 
29             @Override
30             public void onClick(View v) {
31                 SecondFragment second = new SecondFragment();
32                 FragmentManager fm = getFragmentManager();
33                 FragmentTransaction ft = fm.beginTransaction();
34                 ft.replace(R.id.firstFragment, second);
35                 ft.addToBackStack("tag");
36                 ft.commit();
37             }
38         });
39     }
40 
41     @Override
42     protected boolean onBackPressed() {
43         return false;
44     }
45 
46 }
复制代码
复制代码

SecondFragment.java

复制代码
复制代码
 1 package com.example.testdemo;
 2 
 3 import android.os.Bundle;
 4 import android.support.annotation.Nullable;
 5 import android.view.LayoutInflater;
 6 import android.view.View;
 7 import android.view.ViewGroup;
 8 
 9 public class SecondFragment extends BackHandledFragment {
10 
11     private View mView;
12 
13     @Override
14     public View onCreateView(LayoutInflater inflater,
15             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
16         mView = inflater.inflate(R.layout.fragment_second, null);
17         return mView;
18     }
19 
20     @Override
21     protected boolean onBackPressed() {
22         return false;
23     }
24 
25 }
复制代码
复制代码

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

复制代码
复制代码
 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical" >
 6 
 7     <TextView
 8         android:layout_width="wrap_content"
 9         android:layout_height="wrap_content"
10         android:layout_centerInParent="true"
11         android:text="FragmentActivity 父界面"
12         android:textSize="26sp" />
13 
14     <Button
15         android:id="@+id/btnSecond"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:layout_alignParentBottom="true"
19         android:text="跳转到FirstFragment" />
20 
21     <FrameLayout
22         android:id="@+id/firstFragment"
23         android:layout_width="match_parent"
24         android:layout_height="match_parent" >
25     </FrameLayout>
26 
27 </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

复制代码
复制代码
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:background="#e5e5e5"
 6     android:orientation="vertical" >
 7 
 8     <TextView
 9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:layout_centerInParent="true"
12         android:text="SecondFragment"
13         android:textColor="#000000"
14         android:textSize="26sp" />
15 
16 </RelativeLayout>
复制代码
复制代码

 

7.最后奉上实例链接:

http://files.cnblogs.com/_ymw/TestDemo




分类: android solve




本文转自wanqi博客园博客,原文链接:http://www.cnblogs.com/wanqieddy/p/4746959.html,如需转载请自行联系原作者


相关文章
|
11月前
|
Android开发 数据安全/隐私保护 开发者
Android自定义view之模仿登录界面文本输入框(华为云APP)
本文介绍了一款自定义输入框的实现,包含静态效果、hint值浮动动画及功能扩展。通过组合多个控件完成界面布局,使用TranslateAnimation与AlphaAnimation实现hint文字上下浮动效果,支持密码加密解密显示、去除键盘回车空格输入、光标定位等功能。代码基于Android平台,提供完整源码与attrs配置,方便复用与定制。希望对开发者有所帮助。
217 0
|
11月前
|
XML Java Android开发
Android自定义view之网易云推荐歌单界面
本文详细介绍了如何通过自定义View实现网易云音乐推荐歌单界面的效果。首先,作者自定义了一个圆角图片控件`MellowImageView`,用于绘制圆角矩形图片。接着,通过将布局放入`HorizontalScrollView`中,实现了左右滑动功能,并使用`ViewFlipper`添加图片切换动画效果。文章提供了完整的代码示例,包括XML布局、动画文件和Java代码,最终展示了实现效果。此教程适合想了解自定义View和动画效果的开发者。
461 65
Android自定义view之网易云推荐歌单界面
|
9月前
|
安全 数据库 Android开发
在Android开发中实现两个Intent跳转及数据交换的方法
总结上述内容,在Android开发中,Intent不仅是活动跳转的桥梁,也是两个活动之间进行数据交换的媒介。运用Intent传递数据时需注意数据类型、传输大小限制以及安全性问题的处理,以确保应用的健壯性和安全性。
593 11
|
11月前
|
Android开发 开发者
Android企业级实战-界面篇-3
本文是《Android企业级实战-界面篇》系列的第三篇,主要介绍分割线和条形跳转框的实现方法,二者常用于设置和个人中心界面。文章通过具体代码示例展示了如何实现这两种UI组件,并提供了效果图。实现前需准备`dimens.xml`、`ids.xml`、`colors.xml`等文件,部分资源可参考系列第一、二篇文章。代码中详细说明了布局文件的配置,如分割线的样式定义和条形跳转框的组件组合,帮助开发者快速上手并应用于实际项目中。
138 1
|
11月前
|
XML Android开发 数据格式
Android企业级实战-界面篇-2
本文为《Android企业级实战-界面篇》系列第二篇,主要介绍三个UI模块的实现:用户资料模块、关注与粉丝统计模块以及喜欢和收藏功能模块。通过详细的XML代码展示布局设计,包括dimens、ids、colors配置文件的使用,帮助开发者快速构建美观且功能齐全的界面。文章结合实际效果图,便于理解和应用。建议配合第一篇文章内容学习,以获取完整工具类支持。
171 0
|
11月前
|
算法 Java Android开发
Android企业级实战-界面篇-1
本文详细介绍了Android企业级开发中界面实现的过程,涵盖效果展示、实现前准备及代码实现。作者通过自身经历分享了Android开发经验,并提供了`dimens.xml`、`ids.xml`、`colors.xml`和`strings.xml`等配置文件内容,帮助开发者快速构建规范化的UI布局。文章以一个具体的用户消息界面为例,展示了如何使用线性布局(LinearLayout)和相对布局(RelativeLayout)实现功能模块排列,并附带注意事项及使用方法,适合初学者和进阶开发者参考学习。
239 0
|
Android开发 开发者 容器
android FragmentManager 删除所有Fragment 重建
通过本文,我们详细介绍了如何使用 `FragmentManager`删除所有Fragment并重建。通过理解和应用这些步骤,可以在实际开发中更灵活地管理Fragment,满足各种应用场景的需求。希望本文能帮助开发者更好地掌握Fragment管理技巧,提高应用开发效率和代码质量。
272 8
|
程序员 开发工具 Android开发
Android|WebView 禁止长按,限制非白名单域名的跳转层级
如何限制 WebView 仅域名白名单网址能随意跳转,并禁用长按选择文字。
420 2
|
缓存 前端开发 Android开发
Android实战之如何截取Activity或者Fragment的内容?
本文首发于公众号“AntDream”,介绍了如何在Android中截取Activity或Fragment的屏幕内容并保存为图片。包括截取整个Activity、特定控件或区域的方法,以及处理包含RecyclerView的复杂情况。
349 3
|
XML 数据可视化 Android开发
Android应用界面
Android应用界面中的布局和控件使用,包括相对布局、线性布局、表格布局、帧布局、扁平化布局等,以及AdapterView及其子类如ListView的使用方法和Adapter接口的应用。
359 0
Android应用界面

热门文章

最新文章

下一篇
开通oss服务