需要帮助优化Android Fragment代码



有什么方法可以减少代码吗?

正如你在下面看到的,我试图用domain.com/加载一个网络视图?id=1和id=2等等,以及我有很多公共静态类DEMO*如何优化它?

public class WebFragment extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_stack);
}
public static class DEMO1 extends Fragment {
    /** The Fragment's UI **/
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.main, container, false);
        WebView engine = (WebView) v.findViewById(R.id.web_engine);
        engine.loadUrl("http://domain.com/?id=1");
        }
        return v;
    }
}
public static class DEMO2 extends Fragment {
    /** The Fragment's UI **/
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.main, container, false);
        WebView engine = (WebView) v.findViewById(R.id.web_engine);
        engine.loadUrl("http://domain.com/?id=2");
        }
        return v;
    }
}
public static class DEMO3 extends Fragment {
    [... and so on ...]

在构造函数中传递Web视图的URL。。。

public static class Demo extends Fragment {
private String mUrl;
public Demo(String url) {
    this.mUrl = url;
}
/** The Fragment's UI **/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.main, container, false);
    WebView engine = (WebView) v.findViewById(R.id.web_engine);
    engine.loadUrl(mUrl);
    }
    return v;
}
}

我有点喜欢ApiDemos中给出的解决方案。我只复制相关的部分:

public static class CountingFragment extends Fragment {
    int mNum;
    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    static CountingFragment newInstance(int num) {
        CountingFragment f = new CountingFragment();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);
        return f;
    }
    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }
    ...
}

来源:FragmentStack.java

在实例化片段并在onCreate中检索片段时,基本上将变量作为参数提供。碎片基础文档中也展示了相同的代码,可能值得一读。

最新更新