android fragment参数,Android 中为什么要用Fragment.setArguments(Bundle bundle)来传递参数

Fragment在Android3.0开始提供,并且在兼容包中也提供了Fragment特性的支持。Fragment的推出让我们编写和管理用户界面更快捷更方便了。

但当我们实例化自定义Fragment时,为什么官方推荐Fragment.setArguments(Bundle bundle)这种方式来传递参数,而不推荐通过构造方法直接来传递参数呢?为了弄清这个问题,我们可以做一个测试,分别测试下这两种方式的不同

首先,我们来测试下通过构造方法传递参数的情况

public class FramentTestActivity extends ActionBarActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

if (savedInstanceState == null) {

getSupportFragmentManager().beginTransaction()

.add(R.id.container, new TestFragment("param")).commit();

}

}

public static class TestFragment extends Fragment {

private String mArg = "non-param";

public TestFragment() {

Log.i("INFO", "TestFragment non-parameter constructor");

}

public TestFragment(String arg){

mArg = arg;

Log.i("INFO", "TestFragment construct with parameter");

}

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_main, container,

false);

TextView tv = (TextView) rootView.findViewById(R.id.tv);

tv.setText(mArg);

return rootView;

}

}

}

可以看到我们传递过来的数据正确的显示了,现在来考虑一个问题,如果设备配置参数发生变化,这里以横竖屏切换来说明问题,显示如下

发生了什么问题呢?我们传递的参数哪去了?为什么会显示默认值?不急着讨论这个问题,接下来我们来看看Fragment.setArguments(Bundle bundle)这种方式的运行情况

public class FramentTest2Activity extends ActionBarActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout. activity_main);

if (savedInstanceState == null) {

getSupportFragmentManager().beginTransaction()

.add(R.id. container, TestFragment.newInstance("param")).commit();

}

}

public static class TestFragment extends Fragment {

private static final String ARG = "arg";

public TestFragment() {

Log. i("INFO", "TestFragment non-parameter constructor" );

}

public static Fragment newInstance(String arg){

TestFragment fragment = new TestFragment();

Bundle bundle = new Bundle();

bundle.putString( ARG, arg);

fragment.setArguments(bundle);

return fragment;

}

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout. fragment_main, container,

false);

TextView tv = (TextView) rootView.findViewById(R.id. tv);

tv.setText(getArguments().getString( ARG));

return rootView;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值