最近在使用Fragment的过程中遇到一个问题,初步是想在Fragment中创建一个构造函数,构造函数中传递两个自身需要的变量,如下
public class TestFragment extends Fragment { private String name; private String passwd; public TestFragment(String name, String passwd) { super(); this.name = name; this.passwd = passwd; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.main, null); return view; } }
This fragment should provide a default constructor (a public constructor with no arguments) (com.example.TestFragment)
Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead
在增加一个空参数的构造函数可以消去第一个错误,但是第二个却不能,第二个错误说要使用默认构造函数外加setArguments(Bundle)来代替,去android的官网上查看Fragment的例子都是下面这个样子的
CharSequence mLabel; /** * Create a new instance of MyFragment that will be initialized * with the given arguments. */ static MyFragment newInstance(CharSequence label) { MyFragment f = new MyFragment(); Bundle b = new Bundle(); b.putCharSequence("label", label); f.setArguments(b); return f; }
public class TestFragment extends Fragment { private String name; private String passwd; public static TestFragment newInstance(String name, string passwd) { TestFragment newFragment = new TestFragment(); Bundle bundle = new Bundle(); bundle.putString("name", name); bundle.putString("passwd", passwd); newFragment.setArguments(bundle); return newFragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.main, null); return view; } }
Fragment testFragment=TestFragment.newInstance("name","passwd");
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { name = args.getString("name"); passwd = args.getstring("passwd"); } }