ViewPager - can't get the item position - java

I'm working on a collab project. My goal here is to display the ViewPager item position. I have tried several possible solutions such as trying getting from the addOnPageChangeListener and displaying the position, made a function to in IntroView class to get the position but couldn't get what I wanted. Here's my code structure. Any help would be gladly appreciated. Thanks in advance.
InroActivity.java
public class IntroActivity extends DialogFacebookActivity {
private IntroView mIntroView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ChatterApplication.getApplicationComponent().inject(this);
mIntroView = new IntroView(this);
setContentView(mIntroView);
mIntroView.setAdapter(new IntroPagerAdapter(getSupportFragmentManager()));
}
Here's my IntroView.java
public class IntroView extends CoordinatorLayout {
#Bind(R.id.view_pager)
ViewPager mViewPager;
public IntroView(Context context) {
super(context);
init();
}
public IntroView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public IntroView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setAdapter(#NonNull PagerAdapter pagerAdapter) {
mViewPager.setAdapter(pagerAdapter);
}
public void goToNextPage() {
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
}
public int displayItem(){
return mViewPager.getCurrentItem();
}
private void init() {
inflate(getContext(), R.layout.view_intro, this);
ButterKnife.bind(this);
}
}
Here's my IntroFragment.java
public class IntroFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
#Inject
EventBus mEventBus;
IntroView iv;
ViewPager vp;
public IntroFragment() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
ChatterApplication.getApplicationComponent().inject(this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
IntroPageView view;
if (sectionNumber == IntroPagerAdapter.TUTORIAL_PAGE_COUNT) {
view = new IntroPageViewLast(getContext());
} else {
view = new IntroPageView(getContext(), sectionNumber);
}
iv= new IntroView(getContext());
vp =(ViewPager) iv.findViewById(R.id.view_pager);
Toast.makeText(getContext(),"You are in: " + vp.getCurrentItem() ,Toast.LENGTH_LONG).show();
return view;
}
public static IntroFragment newInstance(int sectionNumber) {
IntroFragment fragment = new IntroFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
}
Here's my IntroPageView which is used by my fragment
public class IntroPageView extends RelativeLayout {
#Bind(R.id.intro_skip)
TextView mSkipButton;
#Bind(R.id.intro_tos_disclaimer_link)
TextView disclaimer;
#Bind(R.id.section_image)
ImageView mImageView;
private IntroPageViewListener mEventListener;
public IntroPageView(Context context, int sectionNumber) {
super(context);
init(sectionNumber);
}
public void setListener(IntroPageViewListener listener) {
this.mEventListener = listener;
}
protected void init(int sectionNumber) {
inflate(getContext(), R.layout.view_intro_fragment, this);
ButterKnife.bind(this);
mImageView.setImageResource(IntroPagerAdapter.TUTORIAL_IMAGE_IDS[sectionNumber - 1]);
}
Here's my *IntroPagerAdapter
public class IntroPagerAdapter extends FragmentPagerAdapter {
public static final int[] TUTORIAL_IMAGE_IDS = {
R.drawable.one,
R.drawable.two,
R.drawable.third,
R.drawable.four
};
public static final int TUTORIAL_PAGE_COUNT = TUTORIAL_IMAGE_IDS.length;
public IntroPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
int sectionNumber = position + 1;
return IntroFragment.newInstance(sectionNumber);
}
#Override
public int getCount() {
return TUTORIAL_PAGE_COUNT;
}
}

Turns out I forgot to use the butter ButterKnife.bind(this); while initializing my ViewPager. Hence, I was able to use addOnPageChangeListener to get the position. Here's the solution:
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// Toast.makeText(getApplicationContext(), "You are in.....: " + (position + 1),Toast.LENGTH_LONG).show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Related

onClick for images in ViewPager

I've a image slider made with the help of ViewPager. I want to show different toast messages when clicked in different images loaded by ViewPager, how can i do that?
this my activity where image slider is shown:
public class MainActivity extends AppCompatActivity{
public static final String MAIN = "OTHER";
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN=
{R.drawable.benz2, R.drawable.benz2,
R.drawable.benz2};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
protected void onCreate(...);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new com.example.nepali_test.MyAdapter(MainActivity.this,XMENArray));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
}
and this is the adapter of the viewpager:
public class MyAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
public MyAdapter(Context context, ArrayList<Integer> images) {
this.context = context;
this.images=images;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.slide, view, false);
ImageView myImage = (ImageView) myImageLayout
.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
I tried to make by adding
if (currentPage==1){
Toast.makeText(this, "page 1", Toast.LENGTH_SHORT).show();
}
in init() but it didn't work.
From what i could understand you need to display the toast when clicking on the image in each page of a ViewPager in which case an easy way is to add an onClickListener to your ImageView inside your adapter's instantiateItem method. So you should change/replace your method with this:
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup view, final int position) {
View myImageLayout = inflater.inflate(R.layout.slide, view, false);
ImageView myImage = (ImageView) myImageLayout
.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(), "page "+position, Toast.LENGTH_SHORT).show();
}
});
view.addView(myImageLayout, 0);
return myImageLayout;
}
Try this:
#Override
public Object instantiateItem(View collection, final int pos) { //have to make final so we can see it inside of onClick()
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View page = inflater.inflate(R.layout.YOUR_PAGE, null);
page.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//this will log the page number that was click
Log.i("TAG", "This page was clicked: " + pos);
}
});
((ViewPager) collection).addView(page, 0);
return page;
}
Hope this will work!
Make Image click interface in adapter class
public class MyAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
MyClassImage myClassImage;
public interface MyClassImage{
void imageClick(String id);
}
public ViewPagerAdapter(Context context, ArrayList<Integer> images,MyClassImage myClassImage) {
this.context = context;
this.images=images;
this.myClassImage=myClassImage;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.z_slide_pager_item, view, false);
ImageView myImage = (ImageView) myImageLayout.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
final int id=images.get(position);
final String imgId=String.valueOf(id);
myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myClassImage.imageClick(imgId);
}
});
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
and implement it on your MainActivity class
public class MainActivity extends AppCompatActivity implements MyAdapter.MyClassImage {
public static final String MAIN = "OTHER";
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN= {R.drawable.benz2, R.drawable.benz2, R.drawable.benz2};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
protected void onCreate(...);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new com.example.nepali_test.MyAdapter(MainActivity.this,XMENArray,this));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
}
#Override
public void imageClick(String id) {
Toast.makeText(this, "page "+id, Toast.LENGTH_SHORT).show();
}
Hope it will be helpful to you.
Thanks.

Android volley singleton and custom gridview adapter

I am using a custom gridview adapter to show images with volley singleton. But when I run it it returns the onErrorResponse. It looks like the adapter is not even set properly, is it something with where i set the adapter? I have tried setting it in onCreate but same error.
The adapter class looked fine so I think the problem is in MainActivity.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private final int THUMBNAIL_SIZE = 250;
private final String KEY = "IMAGE";
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
private static final String URLS[] = {
"http://10.0.2.2/Android%20A4_1/germany.png",
"http://10.0.2.2/Android%20A4_1/indonesia.png",
"http://10.0.2.2/Android%20A4_1/japan.png",
"http://10.0.2.2/Android%20A4_1/sarawak.png",
"http://10.0.2.2/Android%20A4_1/singapore.png",
"http://10.0.2.2/Android%20A4_1/switzerland.png",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i = 0; i<URLS.length; i++) {
LoadingImages(URLS[i]);
}
}
private void LoadingImages(String url) {
ImageLoader imageLoader = MySingleton.getInstance(getApplicationContext()).getImageLoader();
imageLoader.get(url, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
Bitmap image = response.getBitmap();
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
bitmaps.add(thumbnail);
GridView gridView = (GridView)findViewById(R.id.grid_layout);
final ImageAdapter imageAdapter = new ImageAdapter(MainActivity.this, bitmaps);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
intent.putExtra(KEY, URLS[i]);
startActivity(intent);
}
});
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.getMessage());
}
});
}
}
The Adapter class:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Bitmap> bitmaps;
public ImageAdapter(Context context, ArrayList<Bitmap> bitmaps) {
this.mContext = context;
this.bitmaps = bitmaps;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.griditems, null);
MyViewHolder myViewHolder = new MyViewHolder(view);
view.setTag(myViewHolder);
}
MyViewHolder myViewHolder = (MyViewHolder)view.getTag();
myViewHolder.img.setImageBitmap(bitmaps.get(i));
return view;
}
public class MyViewHolder {
public ImageView img;
public MyViewHolder(View view) {
img = view.findViewById(R.id.image1);
}
}
}
My Singleton:
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private static Context context;
private MySingleton(Context context){
this.context = context;
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<>(6);
#Override
public Bitmap getBitmap(String url) {
Bitmap bmp = cache.get(url);
if (bmp == null) {
System.out.println("Not in cache");
} else {
System.out.println("In cache");
}
return bmp;
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
System.out.println("Put in cache");
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Main2Activity:
public class Main2Activity extends AppCompatActivity {
private ImageView imageView;
private final String KEY = "IMAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView = (ImageView)findViewById(R.id.imageView);
Bundle bundle = getIntent().getExtras();
String url = bundle.getString(KEY);
LoadingImages(url);
}
private void LoadingImages(String url) {
final ImageLoader imageLoader = MySingleton.getInstance(getApplicationContext()).getImageLoader();
imageLoader.get(url, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
Bitmap bitmap = response.getBitmap();
imageView.setImageBitmap(bitmap);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
}
});
}
}
change This methods
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
To
#Override
public int getCount() {
return bitmaps.size;
}
#Override
public Object getItem(int i) {
return bitmaps.get(i);
}
#Override
public long getItemId(int i) {
return i;
}

How to Stop Automatic Scrolling of Image Slider on Touch Event

I have created an automatic image slider using custom ViewPager Now i want to know how to stop the automatic sliding of images on touch and start the slider again from it was left when touch is released.
Here is my CustomViewPager.java :-
public class CustomViewPager extends ViewPager {
private boolean isPagingEnabled = true;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onTouchEvent(event);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onInterceptTouchEvent(event);
}
public void setPagingEnabled(boolean b) {
this.isPagingEnabled = b;
}
}
Here is ImageAdapter.java :-
public class SlidingImage_Adapter extends PagerAdapter {
Context context;
int images[];
LayoutInflater inflater;
public SlidingImage_Adapter(Context context, int images[]) {
this.context = context;
this.images = images;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = inflater.inflate(R.layout.sliding_images, container, false);
final ImageView imageView = (ImageView) itemView
.findViewById(R.id.image);
imageView.setImageResource(images[position]);
container.addView(itemView, 0);
return itemView;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
Here is Fragment.java where i am using this CustomViewPager :-
public class HomeFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
TextView tv_slider, tv_button;
RelativeLayout dummyView;
CustomViewPager mViewPager;
Timer timer;
final long DELAY_MS = 1000;//delay in milliseconds before task is to be executed
final long PERIOD_MS = 3000;
private static int currentPage = 0;
private static int NUM_PAGES = 0;
int images[] = {R.drawable.ecommerce, R.drawable.digital_marketing, R.drawable.explainer, R.drawable.it_services,
R.drawable.mobile_app, R.drawable.seo, R.drawable.software, R.drawable.webdesign};
SlidingImage_Adapter imageAdapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
tv_slider=(TextView)v.findViewById(R.id.tv_slider);
tv_slider.setTypeface(EasyFonts.robotoLight(this.getActivity()));
tv_button=(TextView)v.findViewById(R.id.tv_button);
tv_button.setTypeface(EasyFonts.robotoLight(this.getActivity()));
mViewPager = (CustomViewPager) v.findViewById(R.id.pager);
imageAdapter = new SlidingImage_Adapter(getActivity(),images);
mViewPager.setAdapter(imageAdapter);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mViewPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
CirclePageIndicator indicator = (CirclePageIndicator)
v.findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
final float density = getResources().getDisplayMetrics().density;
//Set circle indicator radius
indicator.setRadius(3 * density);
NUM_PAGES =images.length;
// Pager listener over indicator
indicator.setOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
switch (pos){
case 0:
tv_slider.setText(getString(R.string.es_content));
break;
case 1:
tv_slider.setText(getString(R.string.dm_content));
break;
case 2:
tv_slider.setText(getString(R.string.ev_content));
break;
case 3:
tv_slider.setText(getString(R.string.it_content));
break;
case 4:
tv_slider.setText(getString(R.string.md_content));
break;
case 5:
tv_slider.setText(getString(R.string.seo_content));
break;
case 6:
tv_slider.setText(getString(R.string.sd_content));
break;
case 7:
tv_slider.setText(getString(R.string.wd_content));
break;
}
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
return v;
}
According to this documentation, the onTouchEvent which you have already overridden is where to look at.
Now instead of calling super.onTouchEvent(event) again as you did in your method. implement your own custom action. by calling super, you're accepting the default behavior.
this is my example code it's working good =>
public class MainActivity extends AppCompatActivity {
final long DELAY_MS = 1000;//delay in milliseconds before task is to be executed
final long PERIOD_MS = 3000;
int currentPage = 0;
public Timer timer;
public Timer swipeTimer;
public static boolean startSlider = true;
public TextView textView;
public LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
layout = (LinearLayout) findViewById(R.id.layout);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == 6) {
currentPage = 0;
}
currentPage++;
textView.setText(String.valueOf(currentPage));
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
if (startSlider){
handler.post(Update);
}
}
}, DELAY_MS, PERIOD_MS);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (startSlider){
startSlider = false;
}else {
startSlider = true;
}
}
});
}
}
i have found a third party library "Library Link" and it has built-in methods for starting and stopping the automatic scrolling.

unable to fetch images in image slider in fragment

When I extend an Activity this works fine, but when extending ActivityFragment I get an error:
unable to resolve constructor
At this line: BaseViewPagerAdapter<String> adapter = new BaseViewPagerAdapter<String>(this). I'm just fetching the image from a URL and displaying it in an image slider. If anyone knows any links or tutorials feel free to suggest me. Thanks.
HomeActivity.java
public class HomeActivity extends Fragment {
private String[] paths = {"http://reviewsimpact.com/wp-content/uploads/2016/04/Patanjali-products-list-1024x385.png",
"https://4.bp.blogspot.com/-3-qgzGwoQ3o/Vuqb1a0g6RI/AAAAAAAAATc/FZjOTm0VUBgXsw3VnWz3RorARUUUgl32g/s1600/Baba%2BRamdev%2BPatanjali%2BProducts%2BList%2Bwith%2BPrice%2Blatest%2B-%2BTipsmonk.jpg",
"http://patanjalistores.com/wp-content/uploads/2015/08/maxresdefault-1920x692.jpg",
"https://aos.iacpublishinglabs.com/question/aq/700px-394px/poems-fruits-vegetables_8d6a91e11da7d63.jpg?domain=cx.aos.ask.com",
"https://i.ytimg.com/vi/2IVR8BrUESQ/maxresdefault.jpg"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
AutoScrollViewPager mViewPager = (AutoScrollViewPager) v.findViewById(R.id.viewPager);
mViewPager = (AutoScrollViewPager)v.findViewById(R.id.viewPager);
BaseViewPagerAdapter<String> adapter = new BaseViewPagerAdapter<String>(this) {
#Override
public void loadImage(ImageView view, int position, String url) {
Picasso.with(getActivity().getApplicationContext()).load(url).into(view);
}
#Override
public void setSubTitle(TextView textView, int position, String s) {
textView.setText("");
}
};
mViewPager.setAdapter(adapter);
adapter.add(initData());
return v;
}
private List<String> initData() {
List<String> data = new ArrayList<>();
Picture picture ;
for (int i = 0 ; i < paths.length ;i++){
data.add(paths[i]);
}
return data;
}
}
BaseBaseViewPagerAdapter.java
public abstract class BaseViewPagerAdapter<T> extends PagerAdapter implements ViewPager.OnPageChangeListener{
private List<T> data = new ArrayList<>();
private Context mContext;
private AutoViewPager mView;
private OnAutoViewPagerItemClickListener listener;
public BaseViewPagerAdapter(List<T> t) {
this.data = t;
}
public BaseViewPagerAdapter(Context context, OnAutoViewPagerItemClickListener listener) {
this.mContext = context;
this.listener = listener;
}
public BaseViewPagerAdapter(Context context, List<T> data) {
this.mContext = context;
this.data = data;
}
public BaseViewPagerAdapter(Context context, List<T> data,OnAutoViewPagerItemClickListener listener) {
this.mContext = context;
this.data = data;
this.listener = listener;
}
public void init(AutoViewPager viewPager,BaseViewPagerAdapter adapter){
mView = viewPager;
mView.setAdapter(this);
mView.addOnPageChangeListener(this);
if (data == null || data.size() == 0){
return;
}
//设置初始为中间,这样一开始就能够往左滑动了
int position = Integer.MAX_VALUE/2 - (Integer.MAX_VALUE/2) % getRealCount();
mView.setCurrentItem(position);
if (!mView.isStart()) {
mView.start();
mView.updatePointView(getRealCount());
}
}
public void setListener(OnAutoViewPagerItemClickListener listener) {
this.listener = listener;
}
public void add(T t){
data.add(t);
notifyDataSetChanged();
mView.updatePointView(getRealCount());
}
public void add(List<T> list){
if (data == null) {
data = new ArrayList<>();
}
data.addAll(list);
notifyDataSetChanged();
mView.start();
mView.updatePointView(getRealCount());
}
public void init(List<T> list){
if (data == null) {
data = new ArrayList<>();
}
data.clear();
data.addAll(list);
notifyDataSetChanged();
if (!mView.isStart()) {
mView.start();
mView.updatePointView(getRealCount());
}
}
#Override
public int getCount() {
return (data == null || data.size() == 0 ) ? 0 : Integer.MAX_VALUE;
}
public int getRealCount(){
return data == null ? 0 : data.size();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView view = (ImageView) LayoutInflater.from(mContext)
.inflate(R.layout.imageview,container,false);
loadImage(view,position, data.get(position % getRealCount()));
container.addView(view);
//设置标题(不知道为什么标题跟图片对不上,所以做了如下处理,有大神看到帮忙看看。。。)
if (mView.getSubTitle() != null){
if (position == 0){
setSubTitle(mView.getSubTitle(),position,data.get((getRealCount() - 1)));
}else {
setSubTitle(mView.getSubTitle(),position,data.get((position - 1) % getRealCount()));
}
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onItemClick(position % getRealCount(),data.get(position % getRealCount()));
}
}
});
return view;
}
public abstract void loadImage(ImageView view,int position,T t);
public abstract void setSubTitle(TextView textView,int position,T t);
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mView.onPageSelected(position % getRealCount());
}
#Override
public void onPageScrollStateChanged(int state) {
}
public interface OnAutoViewPagerItemClickListener<T> {
void onItemClick(int position,T t);
}
}
MainActivity.java
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerLayout.setDrawerShadow(R.drawable.navigation_drawer_shadow, GravityCompat.START);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeActivity();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}

The endless listview charges every element

I know there are a lot of documentation about this topic, but I have a problem with the endless ListView. Each row must show a ProgressBar until the user scrolls, but it doesn't success. When the app starts, all the elements are loaded disappearing all the ProgressBar. Here is all the code.
public class MainActivity extends Activity implements EndlessListView.EndlessListener{
EndlessListView lv;
List<String> listOfElements;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
lv = new EndlessListView(this);
listOfElements = fillList();
EndlessAdapter adp = new EndlessAdapter(this, listOfElements,-1);
lv.setLoadingView();
lv.setAdapter(adp);
lv.fillAdapter(listOfElements);
lv.setListener(this);
layout.addView(lv);
setContentView(layout);
}
public List<String> fillList(){
List<String> listOfElements = new ArrayList<String>();
for (int i = 0; i < 200; i++) {
listOfElements.add("Element "+i );
}
return listOfElements;
}
}
public class EndlessListView extends ListView{
Context context;
private EndlessListener listener;
private EndlessAdapter adapter;
public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EndlessListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EndlessListView(Context context) {
super(context);
}
public void setContext(Context context){
this.context = context;
}
public void setLoadingView() {
LinearLayout layout = new LinearLayout(super.getContext());
//this.addView(layout);
}
public void setAdapter(EndlessAdapter adapter) {
super.setAdapter(adapter);
this.adapter = adapter;
}
public EndlessListener setListener() {
return listener;
}
public void setListener(EndlessListener listener) {
this.listener = listener;
}
public static interface EndlessListener {
}
public void fillAdapter(List<String> data){
adapter.addAll(data);
adapter.notifyDataSetChanged();
}
}
And this is the critical code:
public class EndlessAdapter extends ArrayAdapter<String> {
private List<String> itemList;
private Context ctx;
private int layoutId;
public EndlessAdapter(Context ctx, List<String> itemList, int layoutId) {
super(ctx, layoutId, itemList);
this.itemList = itemList;
this.ctx = ctx;
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public String getItem(int position) {
return itemList.get(position);
}
#Override
public long getItemId(int position) {
return itemList.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = new TextView(ctx);
ProgressBar pg = new ProgressBar(ctx);
if (convertView == null) {
tv = new TextView(ctx);
pg = new ProgressBar(ctx);
convertView = pg;
} else {
pg = (ProgressBar) convertView;
}
//tv.setText(itemList.get(position));
FakeImageLoader fake = new FakeImageLoader(tv, pg, position);
fake.execute();
System.out.println("Me estoy pintando y soy el elemento "
+ itemList.get(position));
return convertView;
}
private class FakeImageLoader extends AsyncTask<String, Void, TextView> {
private TextView tv;
private ProgressBar pg;
private int position;
public FakeImageLoader(TextView tv,
ProgressBar pg, int position) {
this.tv = tv;
this.pg = pg;
this.position = position;
}
protected void onPreExecute() {
}
protected TextView doInBackground(String... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return createItem(position);
}
protected void onPostExecute(TextView text) {
tv = text;
addNewData(tv, pg,position);
}
public TextView createItem(int position) {
TextView text = new TextView(ctx);
text.setText(itemList.get(position));
System.out.println(itemList.get(position));
text.setTextSize(20);
return text;
}
}
public void addNewData(TextView text, ProgressBar pg, int position) {
System.out.println("Entra");
pg.setVisibility(View.INVISIBLE);
text.setText(itemList.get(position));
}
}
Regards.

Categories

Resources