对Java - 理解的newInstance()创建一个片段时, [英] new to java - understanding newInstance() when creating a fragment

查看:106
本文介绍了对Java - 理解的newInstance()创建一个片段时,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建一个新的片段,这个类的构造函数有这个的newInstance这我不知道它做什么,也许你能向我解释它在做什么?

in creating a new fragment, the constructor of this class has this "newInstance" which I am not sure what it does, perhaps you can explain to me what it is doing ?

public class DetailsFragment extends Fragment {
private int mIndex = 0;

public static DetailsFragment newInstance(int index) {

DetailsFragment df = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
df.setArguments(args);
return df;
}

public static DetailsFragment newInstance(Bundle bundle) {
int index = bundle.getInt("index", 0);
return newInstance(index);
}

从我有限的Java方面的知识,我认为这是创建这个类的一个新对象。但如果是这样的话,那么为什么不只是写DetailsFragment DF =新DetailsFragment()主?现在看来似乎是做什么的。

From my limited knowledge of Java, i think it is creating a new object of this class.. but if that is the case,then why not just write DetailsFragment df = new DetailsFragment() in the main ? It seems like it is doing the something.

推荐答案

的newInstance 函数是一个方便的功能就是习惯在Android中使用。该函数的一点是要确保你总是叫 setArguments 创建片段时,因为需要的片段这些参数。你是对的,你是不是要求以这样做事。这仅仅是一个习惯性的模式。

The newInstance function is a convenience function that is customary to use in Android. The point of the function is to make sure you always call setArguments when creating the fragment, because the fragment requires those arguments. You are right that you are not required to do things this way. It is just a customary pattern.

您不能只是创建参数的构造函数,因为Android的需要能够实例那些片段,它不能够提供这些参数。

You cannot just create a constructor with arguments because Android needs to be able to instantiate those fragments and it wouldn't be able to supply those parameters.

这篇关于对Java - 理解的newInstance()创建一个片段时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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