Android Fragment 构造函数和java不太一样,可以模仿原生的写法,如下:
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; }
下面是一个Test示例:
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; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { name = args.getString("name"); passwd = args.getstring("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; } }
调用:
Fragment testFragment=TestFragment.newInstance("name","passwd");