例如我在我的TestFragment中写一个这样的构造函数
public TestFragment(int position) {
this.position = position;
}
会报这样的错误
Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead less...

参考了下面的文章后解决:(大概意思时官方有其他的方法让我们用)
https://blog.youkuaiyun.com/anobodykey/article/details/22503413
public static TestFragment newInstance(int position) {
Bundle args = new Bundle();
args.putInt("position",position);
AwosInfoFrag fragment = new AwosInfoFrag();
fragment.setArguments(args);
return fragment;
}
然后在MainActivity中调用即可:
TestFragment test=TestFragment.newInstance(i);
本文讲解了在Android开发中如何正确使用Fragment的构造函数,避免直接使用非默认构造函数,而是采用newInstance方法传递参数,同时展示了如何在MainActivity中调用此方法实例化Fragment。
1万+

被折叠的 条评论
为什么被折叠?



