bhargav hada bhargav hada - 5 months ago 71
Android Question

How to set data in viewpager?

Here, in this viewpageradapter class is using to set json data, how can I set data in viewpager. I can try to implement but I don't know how can be achieving this.

public class ViewPagerAdaptor extends PagerAdapter {
Context context;


ImageView imageView;
TextView tv_date;
TextView tv_content;
LayoutInflater inflater;
ArrayList<Model> arrayList;

public ViewPagerAdaptor(Context context, ArrayList<Model> arrayList) {
this.context = context;
this.arrayList = arrayList;
}

@Override
public int getCount() {
return arrayList.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
return view==(LinearLayout)object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {

inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);

imageView= (ImageView) itemView.findViewById(R.id.image);
tv_date= (TextView) itemView.findViewById(R.id.tv_date);
tv_content= (TextView) itemView.findViewById(R.id.tv_content);




// Capture position and set to the ImageView
imageView.setImageResource(flag[position]);

// Capture position and set to the TextViews
tv_date.setText(date[position]);
tv_content.setText(content[position]);

((ViewPager) container).addView(itemView);

return itemView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {

((ViewPager) container).removeView((LinearLayout) object);
}
}

Answer

You need to get it from the arraylist and bind it to the UI in instantiateItem() method.

See sample code below,

@Override
public Object instantiateItem(ViewGroup container, int position) {

    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.viewpager_item, container, false);

    imageView= (ImageView) itemView.findViewById(R.id.image);
    tv_date= (TextView) itemView.findViewById(R.id.tv_date);
    tv_content= (TextView) itemView.findViewById(R.id.tv_content);

    Model item = (Model) arrayList.get(position);

    // Capture position and set to the ImageView
    imageView.setImageResource(item.getFlag());

    // Capture position and set to the TextViews
    tv_date.setText(item.getDate());
    tv_content.setText(item.getContent());

    ((ViewPager) container).addView(itemView);

    return itemView;
}
Comments