2011-07-25 101 views
3

如何創建自定義ViewPager? 要在ViewPager實例化一個網頁是這樣的:自定義ViewPager

  public Object instantiateItem(View collection, int position) { 
        TextView tv = new TextView(cxt); 
        tv.setText("Bonjour PAUG " + position); 
        tv.setTextColor(Color.WHITE); 
        tv.setTextSize(30); 

        ((ViewPager) collection).addView(tv,0); 

        return tv; 
      } 

是有辦法膨脹這樣從一個適配器擴展一個類:

public View getView(int position, View convertView, ViewGroup parent) { 
    View v = convertView; 
    if (v == null) { 
     LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = vi.inflate(R.layout.the_layout, null); 
    } 
    CustomView cv = items.get(position); 
    if (cv != null) { 
      TextView text = (TextView) v.findViewById(R.id.text); 
      if (text != null) { 
        ticker.setText(cv.getText()); 
      } 

回答

3

這僅僅是一個例子,但它工作的很好。

public Object instantiateItem(View collection, int position) { 
     LayoutInflater inflater = (LayoutInflater)cxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View layout = inflater.inflate(R.layout.search_result, null); 
     // 
     TextView title = (TextView)layout.findViewById(R.id.search_result_title); 
     TextView body = (TextView)layout.findViewById(R.id.search_result_body); 
     TextView byline = (TextView)layout.findViewById(R.id.search_result_byline); 
     TextView day = (TextView)layout.findViewById(R.id.search_result_date_day); 
     TextView month = (TextView)layout.findViewById(R.id.search_result_date_month); 
     TextView year = (TextView)layout.findViewById(R.id.search_result_date_year); 
     // 
     title.setText(list_title.get(position).toString()); 
     body.setText(list_body.get(position).toString()); 
     day.setText(list_day.get(position).toString()); 
     month.setText(list_month.get(position).toString()); 
     year.setText(list_year.get(position).toString()); 
     byline.setText(list_byline.get(position).toString()); 
     // 
     ((ViewPager) collection).addView(layout,0); 
     return layout; 
    } 
-2

子類的PagerAdapter類並重寫相應的方法。其實,如果你看源代碼,你只能傳遞一個PagerAdapter對象給setAdapter(),所以答案是否定的。

0

Tsunaze是正確的。此外,還有另一種方法。如果您使用Fragments來設置UI視圖,則可以使用FragmentPagerAdapter中的getItem(int position),然後使用Fragment類中的onCreateView方法。

@Override 
public Fragment getItem(int position) { 
    // TODO Auto-generated method stub 

    Log.d(TAG, "getItem"); 

    return ImageListFragment.newInstance(position, mList); 
} 
相關問題