最近,我厌倦了在创建Fragments
时必须不断地知道String
键才能将参数传递给Bundles
。因此,我决定为我的Fragments
创建构造函数,它将接受我想要设置的参数,并使用正确的String
键将这些变量放入Bundles
中,从而消除了其他Fragments
和Activities
需要知道这些键的需要。
public ImageRotatorFragment() {
super();
Log.v(TAG, "ImageRotatorFragment()");
}
public ImageRotatorFragment(int imageResourceId) {
Log.v(TAG, "ImageRotatorFragment(int imageResourceId)");
// Get arguments passed in, if any
Bundle args = getArguments();
if (args == null) {
args = new Bundle();
}
// Add parameters to the argument bundle
args.putInt(KEY_ARG_IMAGE_RES_ID, imageResourceId);
setArguments(args);
}
然后我像往常一样拉出这些论点。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
// Set incoming parameters
Bundle args = getArguments();
if (args != null) {
mImageResourceId = args.getInt(KEY_ARG_IMAGE_RES_ID, StaticData.getImageIds()[0]);
}
else {
// Default image resource to the first image
mImageResourceId = StaticData.getImageIds()[0];
}
}
然而,林特对此提出了异议,他说没有带有其他参数的构造函数的Fragment
的子类,甚至需要我使用@SuppressLint("ValidFragment")
来运行应用程序。问题是,这段代码运行得非常好。我可以使用ImageRotatorFragment(int imageResourceId)
或老方法ImageRotatorFragment()
,并对其手动调用setArguments()
。当Android需要重新创建片段时(方向改变或内存不足),它会调用ImageRotatorFragment()
构造函数,然后传递与我的值相同的参数Bundle
,这些值被正确设置。
因此,我一直在搜索“建议”的方法,并看到许多使用newInstance()
创建带参数的Fragments
的示例,这似乎与我的构造函数做的事情是一样的。所以我自己做了测试,它和以前一样完美无瑕,除了Lint对它的抱怨。
public static ImageRotatorFragment newInstance(int imageResourceId) {
Log.v(TAG, "newInstance(int imageResourceId)");
ImageRotatorFragment imageRotatorFragment = new ImageRotatorFragment();
// Get arguments passed in, if any
Bundle args = imageRotatorFragment.getArguments();
if (args == null) {
args = new Bundle();
}
// Add parameters to the argument bundle
args.putInt(KEY_ARG_IMAGE_RES_ID, imageResourceId);
imageRotatorFragment.setArguments(args);
return imageRotatorFragment;
}
我个人发现使用构造函数比使用newInstance()
和传递参数要普遍得多。我相信你可以在Activities中使用同样的构造函数技术,Lint不会对此抱怨。所以基本上我的问题是,为什么谷歌不希望你对Fragments
**?** 使用带参数的构造函数
我唯一的猜测是,这样您就不会在不使用Bundle
的情况下尝试设置实例变量,因为在重新创建Fragment
时不会设置该变量。通过使用static newInstance()
方法,编译器不允许您访问实例变量。
public ImageRotatorFragment(int imageResourceId) {
Log.v(TAG, "ImageRotatorFragment(int imageResourceId)");
mImageResourceId = imageResourceId;
}
我仍然不认为这是禁止在构造函数中使用参数的足够理由。其他人对此有什么见解吗?
发布于 2016-07-08 19:38:20
Android只会使用默认构造函数重新创建它杀死的片段,所以我们在其他构造函数中所做的任何初始化都将是lost.Hence数据将丢失。
https://stackoverflow.com/questions/14654766
复制相似问题