需要帮助优化Android片段代码吗

需要帮助优化Android片段代码吗,android,webview,fragment,Android,Webview,Fragment,有没有办法减少代码 正如您在下面看到的,我尝试加载一个domain.com/?id=1和id?=2的webview,以此类推 我有许多公共静态类演示*如何优化它 public class WebFragment extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setConten

有没有办法减少代码

正如您在下面看到的,我尝试加载一个domain.com/?id=1和id?=2的webview,以此类推 我有许多公共静态类演示*如何优化它

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 ...]

在构造函数中传递webview的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中给出的解决方案。我将只复制相关的bit'n片段:

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;
    }

    ...
}
资料来源:


基本上,在实例化片段并在onCreate中检索它时,将变量作为参数提供。相同的代码在中进行了说明,这可能值得一读。

请确保您的布局文件也