有没有办法减少代码?
如下所示,我尝试使用domain.com/?id=1和id?= 2加载webview,依此类推 我有很多公共静态类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 ...]
答案 0 :(得分:1)
在构造函数中传递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;
}
}
答案 1 :(得分:0)
我有点像ApiDemos中给出的解决方案。我只会复制相关的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中检索时,您基本上将变量作为参数提供。 fragments fundamentals documentation中说明了相同的代码,值得一读。