pagerAdapter引用编程的布局android

时间:2012-09-15 23:22:41

标签: android

我通常使用寻呼机适配器滚动浏览不同的布局,但这次我的布局是用java代码而不是xml创建的。通常在选择资源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;
}

...

}
}

1 个答案:

答案 0 :(得分: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.
}