0

我通常使用寻呼机适配器滚动浏览不同的布局,但这次我的布局是用 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;
}

...

}
}
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 回答