2017-04-11 139 views
-4

有一個名稱列表,我想在移動屏幕上一次顯示一個名稱,並滑動該活動以查看另一個名稱。嘗試使用viewpager,但成功地多次顯示一個文本視圖,而不是如何在viewpager中實現列表。一次顯示一個列表項 - Android

+1

發佈您的代碼? – user2025187

回答

1

您必須爲此創建自定義適配器,該適配器將包含您的數組列表,並將其填充到TextView中。

首先要定義適配器

public class ViewPagerAdapter extends PagerAdapter { 
// Declare Variables 

Context context; 
int[] flag; 
LayoutInflater inflater; 
int pos; 
public ViewPagerAdapter(Context context, int[] flag) { 
    this.context = context; 
    this.flag = flag; 
} 
public ViewPagerAdapter (Context context, int[] flag, int position){ 
    this.context = context; 
    this.flag = flag; 
    this.pos = position; 
} 

@Override 
public int getCount() { 
    return flag.length; 
} 

@Override 
public boolean isViewFromObject(View view, Object object) { 
    return view == ((RelativeLayout) object); 
} 
@Override 
public Object instantiateItem(ViewGroup container, int position) { 

    // Declare Variables 

    TextView txt; 

    inflater = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View itemView = inflater.inflate(R.layout.viewpager_item, container, 
      false); 
    // Locate the ImageView in viewpager_item.xml 
    txt= (TextView) itemView.findViewById(R.id.flag); 
    // Capture position and set to the ImageView 
    txt.setText(flag[position]); 
    txt.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) {    
     } 
    }); 
    // Add viewpager_item.xml to ViewPager 
    ((ViewPager) container).addView(itemView); 

    return itemView; 
} 
@Override 
public void destroyItem(ViewGroup container, int position, Object object) { 
    // Remove viewpager_item.xml from ViewPager 
    ((ViewPager) container).removeView((RelativeLayout) object); 
} 
} 

現在加上適配器將viewPager這樣

adapter = new ViewPagerAdapter(Image.this, flag);//Here Flag is array 
    viewPager.setAdapter(adapter); 
    viewPager.setCurrentItem(possition); 

希望這有助於