0

Fragment 型の getItem(int position) メソッドがあります。スイッチとケースステートメントを使用しようとしていたすべてのページが異なることを意味する約100ページ以上があります。すべてのケースは、以下に示すように Fragment を拡張する新しいクラスを返します。

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.

非常に時間がかかる switch/case ステートメントを使用するよりも、これを行う方が簡単ですか。ありがとう

4

2 に答える 2

1

はい。もっと簡単な方法があります

Page createPage(int index)
{
    // ignore the damn index
    return new Page();
}

関数が行っているのと同じことを行います。作成中のページを格納する変数を保存するために何もしていないようです。

一方、それをどこかに保存したい場合は、クラス (この関数が存在する場所) に配列を含めることができます。クラスが本であるとします。

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

または遅延初期化

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];
    }
}
于 2013-04-01T17:03:55.380 に答える
1

関数を持つオブジェクトを作成したい

Page getPage(){
    return new Page();
}

各ページには独自の属性、おそらく文字列などがあると思います。したがって、これらの値をに保存ArrayList<String>し、インデックスに従ってページに設定できます

Page getPage(int index){
    Page p = new Page();
    String attr = youArrayList.get(index);
    p.setAttrMethod(attr);
    return p;
}
于 2013-04-01T17:27:14.830 に答える