为什么不建议使用简单的getter setter将对象传递给片段 [英] Why its not recommended to pass object to fragment with simple getter setter

查看:63
本文介绍了为什么不建议使用简单的getter setter将对象传递给片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android的新手,我想知道为什么不建议使用这种简单的参数传递方法.

I'm new to android, I wonder why this easy method for parameter passing is not recommended.

class DemoFragment extends Fragment{
    private MyObject myObject;
    public void setMyObject(MyObject myObject){
        this.myObject = myObject;
    }
}

DemoFragment fragmentDemo = new DemoFragment();
fragmentDemo.setMyObject(myObject);

推荐答案

Android提供的将参数传递给Fragments的机制是使用Bundles,这与活动到活动"数据传递中的技术相同.

The mechanism that Android provides for parameter passing to Fragments is using Bundles, which is the same technique in Activity to Activity data passing.

在创建片段时,使用所需的键值调用其 setArguments(Bundle bundle)方法.

When creating your Fragment, call its setArguments(Bundle bundle) method with the desired key-values that you want.

另一个优点是,您可以在设备的配置更改(例如方向更改)期间保留此参数.

Also another advantage is that you can persist this arguments during configuration changes in the device, like the orientation change.

使用getter和setter方法通常不是一个坏习惯,但是在尝试重新发明轮子之前,最好充分利用本机API.

Using getters and setters is not a bad practice generally, but you better take the most out of the native APIs before trying to reinvent the wheel.

这篇关于为什么不建议使用简单的getter setter将对象传递给片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆