在Fragment中新建帶參數的構造函數時報的錯

 例如我在我的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.csdn.net/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);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章