google官方推荐用setArgument来传参而不是用构造函数。
因为当切换横竖屏时,Fragment会调用自己的无参构造函数,那么在构造函数传参就会失效。
public class FramentTestActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//切换横竖屏后savedInstanceState就不为null,所以只有第一次进来时才会调用,如果不判断的话,切换横竖屏时又会在原fragment基础上又new 一个Fragment,这样就有2个fragment重叠了。
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;
}
}
}