在增長一個空參數的構造函數能夠消去第一個錯誤,可是第二個卻不能,第二個錯誤說要使用默認構造函數外加setArguments(Bundle)來代替,去android的官網上查看Fragment的例子都是下面這個樣子的java
/** * 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; }
依葫蘆畫瓢,去掉帶參的構造函數,建立一個newInstance函數,以下android
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所依賴的Activity中,用如下語句建立Fragment實例便可ide
Fragment testFragment=TestFragment.newInstance("name","passwd");
對於從Activity傳遞到Fragment中的參數咱們只須要在Fragment的onCreate中獲取就能夠了函數
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { name = args.getString("name"); passwd = args.getstring("passwd"); } }