更简单的方式来使用的switch / case语句中的Java的Android [英] Easier way to use Switch/Case Statement in Java Android
问题描述
我型片段的的getItem(INT位置)的方法。我有大约100多页意味着每一页不同的是,我试图用switch和case语句。每一种情况下返回一个新的类是延伸片段,如下所示。
I have a getItem(int position) method of type Fragment. I have about more than 100 pages meaning every page is different I was trying to use switch and case statement. Every case returns a new class which is extends Fragment as shown below.
public class Pages{
public static class Page1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
final Button search = (Button) rootView.findViewById(R.id.clicktosearch);
final EditText number = (EditText)rootView.findViewById(R.id.number);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i = 0; i < MainActivity.Help.arr.length; i++){
if(number.getText().toString().equals(MainActivity.Help.arr[i])){
MainActivity.mViewPager.setCurrentItem(i);
}
}
}
});
WebView webview = (WebView) rootView
.findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/2.html");
return rootView;
}
}
}
public Fragment getItem(int position) {
switch(position){
case 1:
Pages.Page1 page1 = new Pages.Page2();
return page1; //same with other pages in different cases.
有没有更容易做到这一点,而不是使用开关/ case语句,这将需要很长的。谢谢
Is there any easier to do this rather than using switch/case statement, which will take really long. Thanks
推荐答案
是的。还有一个更简单的方法
Yes. There is an easier way
Page createPage(int index)
{
// ignore the damn index
return new Page();
}
会做同样的事情,你的函数是做。既然你似乎没有做任何事情,以节省存储正在创建的页面中的变量。
Will do the same thing your function is doing. Since you don't seem to be doing anything to save the variable which stores the page being created.
在另一方面,如果要存储在某个地方,你可以在类(在存在此功能)一个阵列 - 说类是一本书
On the other hand if wanted to store it somewhere you could have a array in the class (where this function exists) - say the class is a book.
public class Book
{
private Page [] p;
public Book()
{
p = new Page[1000];
for(int i = 0; i < 1000; ++i)
p[i] = new Page();
}
public Page createPage(int index)
{
return p[index];
}
}
或延迟初始化
Or a lazy initialization
public class Book
{
private Page [] p;
public Book()
{
p = new Page[1000];
}
public Page createPage(int index)
{
if (p[index) != null)
return p[index];
p[index] = new Page();
return p[index];
}
}
这篇关于更简单的方式来使用的switch / case语句中的Java的Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!