Bottom Navigation Activity之Fragment与Activity的四点不同

发布于:2023-01-04 ⋅ 阅读:(322) ⋅ 点赞:(0)

AS的新建工程模板里有一种是Bottom Navigation Activity,这种模板创建的工程是app里最常见的底部导航形式。这种形式每点一下底部的导航按键,就会跳到相应Fragment页面。在程序里,每一个页面对应的是一个Fragment,几个Fragment组成一个Activity,每个Fragment分别与不同的layout相关连,从感官上看Fragment与Activity非常相似。那么在使用上二者有什么区别呢?本人经过几天的使用,仅就发现的比较表浅的四点不同,做一介绍。

一、加载页面显示的方法不同

1、Activity

通过oncreate()方法,关连layout的方法是:setContentView(布局ID);

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
}

2、Fragment

onCreateView()方法,关连layout的方法是inflater.inflate(布局ID,container,false),并且将inflater.inflate()方法返回的View值赋值给root,将root返回给Activity.


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
       
        View root = inflater.inflate(R.layout.fragment_home, container, false);
             
        return root;
    }

 二、关联layout控件方法不同

1、Activity

关联layout内控件的方法:this.findViewById(控件id)

Button button;
button=this.findViewById(R.id.button);

2、Fragment

关联layout内控件的方法:root.findViewById(控件id)

View root = inflater.inflate(R.layout.fragment_home, container, false);
Button button;
button=root.findViewById(R.id.button);

三、利用Intent实现页面跳转的方式不同

1、Activity

new Intent()第一个参数是当前Activity1.this,第二个参数是要跳转的Activity2.class。

Intent intent =new Intent(Activity1.this, Activity2.class);
startActivity(intent);

2、Fragment

new Intent()第一个参数是getActivity(),第二个参数是要跳转的Activity2.class。

Intent intent =new Intent(getActivity(), Activity2.class);
startActivity(intent);

四、SharedPreferences类的使用不同

1、Activity

定义SharedPreferences的格式是:this.getSharedPreferences(SharedPreferences名,this.MODE_PRIVATE)。

SharedPreferences sp_document;
sp_document=this.getSharedPreferences("sp_document",this.MODE_PRIVATE);

2、Fragment

定义SharedPreferences的格式是:Objects.requireNonNull(getActivity()).getSharedPreferences(SharedPreferences名,getActivity().MODE_PRIVATE)。

SharedPreferences sp_document;
sp_document=Objects.requireNonNull(getActivity()).getSharedPreferences("sp_document", getActivity().MODE_PRIVATE);

五、规律总结

Activity中用到this的地方,在Fragment中不能用,要用其他形式替换,规律有两点:

1、this用root代替

Activity中关联控件的this.findViewById方法的this,Fragment中用inflater.inflate()赋值的那个变量代替(一般为root)。

2、this用getActivity()代替

当前Activity.this中的this,用getActivity()代替。this.getSharedPreferences中的this也可以用getActivity()代替,系统会自动提醒更改为Objects.requireNonNull(getActivity())。


网站公告

今日签到

点亮在社区的每一天
去签到