android中Fragment的构造函数

最近在使用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;
	}

}

结果eclipse报出两个错:

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;
    }

既然人家这么写例子肯定还是有道理的,我们只需要依葫芦画瓢就可以了,去掉带参的构造函数,创建一个newInstance函数,如下

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实例即可

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");
        }
}


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页