Android中Framgment的构造函数

在增长一个空参数的构造函数能够消去第一个错误,可是第二个却不能,第二个错误说要使用默认构造函数外加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");  
        }  
}
相关文章
相关标签/搜索