代码不规范,这个错误是在提示你需要添加一个空的构造函数
错误2 Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead(Error when building APK in android studio打包时报错)
这个错误说要使用默认构造函数外加setArguments(Bundle)来代替,去android的官网上查看Fragment的例子都是下面这个样子的
/** * 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; }
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"); }