0

私は通常、ページャー アダプターを使用してさまざまなレイアウトをスクロールしますが、今回はレイアウトを xml ではなく Java コードで作成しました。通常、リソース ID を選択するときは、R.layout.file を参照します。Java コードでレイアウトを作成したので、リソースを参照する方法がわかりません。誰もこれを行う方法を知っていますか?

参照したい、作成したレイアウトのサンプル コード:

LinearLayout ParentLayout = new LinearLayout(getApplicationContext());
ParentLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
ParentLayout.setOrientation(LinearLayout.VERTICAL);

通常、ページャー アダプターの場合、次のようなものがあります。

public class MyPagerAdapter extends PagerAdapter {


@Override
public int getCount() {
    return 3;
}

public Object instantiateItem(View collection, int position){
    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

     int resId = 0;
     switch (position) {
     case 0:
         resId = R.layout.xmlfile1; //I want to reference the ParentLayout I created above
         break;
     case 1:
         resId = R.layout.xmlfile2;
         break;
     case 2:
         resId = R.layout.xmlfile2; 
         break;

}
     View view = inflater.inflate(resId, null);
     ((ViewPager) collection).addView(view, 0);
     return view;
}

...

}
}
4

1 に答える 1

0

あなたはこれを試すことができます:

public Object instantiateItem(View collection, int position){
    LayoutInflater inflater = (LayoutInflater) collection.getContext()
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

 int resId = 0;
 View view = null;
 switch (position) {
 case 0:
     view = createView(); // the layout you create above
     break;
 case 1:
     resId = R.layout.xmlfile2;
     view = inflater.inflate( resId, null );
     break;
 case 2:
     resId = R.layout.xmlfile2; 
     view = inflater.inflate( resId, null )
     break;

 }
 ((ViewPager) collection).addView(view, 0);
 return view;
}

View createView(){
     // create your layout right here.
}
于 2012-09-16T02:59:22.430 に答える