片段继承与newInstance模式

时间:2016-01-15 13:31:34

标签: android performance android-fragments inheritance fragment

使用newInstance模式进行片段继承的正确方法是什么?

例如,如果我们有一个片段MyFragment继承自另一个具有newInstance模式的片段SuperFragment - > https://stackoverflow.com/a/28855715/5125212

public class SuperFragment extends Fragment{
    public static SuperFragment newInstance(int var1, boolean var2){
        SuperFragment fragment = new SuperFragment();
        Bundle b = new Bundle();
        b.putInt("my_var1", var1);
        b.putBoolean("my_var2", var2);
        fragment.setArguements(b);
        return fragment
    }
// All other methods
}

这会在" super":

上出现错误
public class MyFragment extends SuperFragment{
    public static MyFragment newInstance(int var1, boolean var2){
        return super.newInstance(int var1, var2);
    }
// All other methods
}

这会在构造函数上出错,因为我们应该避免使用非默认的构造函数:

public class MyFragment extends SuperFragment{
    public MyFragment(int var1, boolean var2){
        newInstance(var1, var2);
    } 
// All other methods
}

我发现这不会有任何错误,但我不喜欢它,因为它是semms得到递归:

public class MyFragment extends SuperFragment{
    public static SuperFragment newInstance(int var1, boolean var2){
        return newInstance(var1,var2);
    }
}

2 个答案:

答案 0 :(得分:2)

找到它!

超级片段:

public class SuperFragment extends Fragment{
    public static Bundle setArgs(int var1, boolean var2){
        Bundle b = new Bundle();
        b.putInt("my_var1", var1);
        b.putBoolean("my_var2", var2);
        return b;
    }
// All methods you want in the super fragment, so they will be in the 
// inherit fragment too
}

继承片段:

public class MyFragment extends SuperFragment{
    public static MyFragment newInstance(int var1, boolean var2){
        MyFragment fragment = new MyFragment();
        fragment.setArguments(setArgs(var1,var2));
        return fragment;
    }
// All other methods that you only want them on the inherit (this)     
// fragment
}

答案 1 :(得分:0)

您不必创建重载的构造函数。您将数据传递给newInstanace(var1, var2),然后您会这样做:

public static MyFragment newInstance(int var1, int var2)
{
  MyFragment fragment = new MyFragment(); // default constructor by android system
  Bundle b = new Bundle();
  b.putInt("my_var1", var1);
  b.putInt("my_var2", var2);

fragment.setArguements(b);

return fragment
}

然后在onCreateView

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        int var1 = arguments.getInt("my_var1", 0);

<强>更新

无法通过newInstance模式进行继承,因为无法覆盖静态方法。更重要的是,如果你没有默认的构造函数,那么重载默认构造函数

将是一个编译时错误