I have image slider in android studio, but images array from inside project.
I want to use images from JSON, how to the best solution..
this is my adapter
public class adapter_image_slider extends PagerAdapter {
Context mContext;
public adapter_image_slider(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return sliderImagesId.length;
}
private int[] sliderImagesId = new int[]{
R.drawable.imghome1, R.drawable.imghome2, R.drawable.imghome3,
};
#Override
public boolean isViewFromObject(View v, Object obj) {
return v == ((ImageView) obj);
}
#Override
public Object instantiateItem(ViewGroup container, int i) {
ImageView mImageView = new ImageView(mContext);
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mImageView.setImageResource(sliderImagesId[i]);
((ViewPager) container).addView(mImageView, 0);
return mImageView;
}
#Override
public void destroyItem(ViewGroup container, int i, Object obj) {
((ViewPager) container).removeView((ImageView) obj);
}
}
and this is my main activity :
public class activity_img_slider_json extends Fragment {
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN= {R.drawable.imghome1,R.drawable.imghome2,R.drawable.imghome3,};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_img_slider_json,null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
super.onCreate(savedInstanceState);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager)getActivity().findViewById(R.id.pager);
mPager.setAdapter(new adapter_img_slider_json(getActivity(), XMENArray));
CircleIndicator indicator = (CircleIndicator)getActivity().findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
}
}
Thanks For Attention.
Related
How would I turn my swipe-able ViewPager into a auto looping slideshow? I'v read other post referencing to use a Handler or Timer but I'm not sure which one would be best. Iv posted my code below.
Update:
After following some old posts and comments Iv been trying to initiate a timer to loop through the ViewPager slides. The issue is now the Timer is not working, also not getting any errors either. Any thoughts? Iv added the Timer code to the MainActivity code below.
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ViewPager viewPager;
customSwipeAdapter swipeAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
swipeAdapter = new customSwipeAdapter(this);
viewPager.setAdapter(swipeAdapter);
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
int currentPage = 0;
int NUM_PAGES = 3;
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
});
}
}, 500, 3000);
}
}
CustomSwipeAdapter.java
public class customSwipeAdapter extends PagerAdapter {
private int [] image_resources = {R.drawable.SlideOne,R.drawable.SlideTwo,R.drawable.SlideThr,R.drawable.SlideFour};
private Context context;
private LayoutInflater layoutInflater;
public customSwipeAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (LinearLayout)object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView);
imageView.setImageResource(image_resources[position]);
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((LinearLayout)object);
}
}
On my login activity I would like to have a banner (3 actually) which would switch by certain time. Just like news on a website. With an arrow to pass to the next one, but mainly that passes automatically.
An example of what I want, these images on Tinder login screen switch when I swipe or just wait:
How do I do something like this on Android? Is there a way to do it natively? or at least is there a external resource for that?
Try this code,
public class TestActivity extends AppCompatActivity {
int images[] = {R.drawable.ic_earth, R.drawable.oval_btn,
R.drawable.ic_group_black_24dp, R.drawable.ic_earth};
ImagePagerAdapter myAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tests);
ViewPager viewPager = findViewById(R.id.viewPager);
myAdapter = new ImagePagerAdapter(TestActivity.this, images);
viewPager.setAdapter(myCustomPagerAdapter);
setupViewPager(viewPager);
}
int currentPage = 0;
Timer timer;
final long DELAY_MS = 500;
final long PERIOD_MS = 3000;
int NUM_PAGES = 4;
private void setupViewPager(final ViewPager viewPager) {
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
timer = new Timer(); // This will create a new Thread
timer .schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
}
public class ImagePagerAdapter extends PagerAdapter {
Context context;
int images[];
LayoutInflater layoutInflater;
public ImagePagerAdapter(Context context, int images[]) {
this.context = context;
this.images = images;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = layoutInflater.inflate(R.layout.item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
container.addView(itemView);
//listening to image click
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
}
I am developing a simple gallery app .
I have 2 problems :
First problem :
When I touch a specific image in my GridView to show in the fullscreen activity (viewpager activity) it always shows the first image in the GridView gallery!!! not the one I touched!!!
But ViewPager work correctly .
Second problem:
I want to zoom in the ViewPager activity
I tried a library (chrisbanes:phtoview) but it has some issues with ViewPager
Summary :
I want my gallery app to work normal. GridView gallery (you can swipe and pinch to zoom images)
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ViewPager slider;
private SliderAdapter sliderAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
slider=findViewById(R.id.slider);
sliderAdapter=new SliderAdapter(this);
slider.setAdapter(sliderAdapter);
}
private class SliderAdapter extends PagerAdapter{
private Context context;
private LayoutInflater inflater;
public SliderAdapter(Context context) {
this.context = context;
}
int[] list_img={R.drawable.ferari,R.drawable.ferrari,R.drawable.ferrarilogoo,R.drawable.yellowferrariiii,R.drawable.models,R.drawable.applogo,R.drawable.carfront,R.drawable.california,R.drawable.laferrari
};
#Override
public int getCount() {
return list_img.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view==object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position) {
inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.item_slider,container,false);
ImageView imageView=view.findViewById(R.id.img_item);
imageView.setImageResource(list_img[position]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(context,Fullscreen.class);
intent.putExtra("Ferrari",position);
startActivity(intent);
}
});
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ImageView)object);
}
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new ViewGroup.LayoutParams(230, 250));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(3, 3, 3, 3);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
public Integer[] mThumbIds = {
R.drawable.ferari, R.drawable.models,
R.drawable.ferrarihd,
R.drawable.ferrari,
R.drawable.yellowferrariiii,
R.drawable.models,
R.drawable.home,
R.drawable.carfront,
R.drawable.villa,
R.drawable.derrarii,
R.drawable.laferrari,
R.drawable.realestate,
R.drawable.carfront,R.drawable.california,R.drawable.laferrari
};
}
FullscreenviewActivity.java
public class FullScreenViewActivity extends AppCompatActivity {
private ViewPager slider;
private SliderAdapter sliderAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen_view);
slider=findViewById(R.id.slider);
sliderAdapter=new SliderAdapter(this);
slider.setAdapter(sliderAdapter);
slider.setPageTransformer(false, new ViewPager.PageTransformer() {
#Override
public void transformPage(View page, float position) {
// do transformation here
final float normalizedposition = Math.abs(Math.abs(position) - 1);
page.setScaleX(normalizedposition / 2 + 0.5f);
page.setScaleY(normalizedposition / 2 + 0.5f);
//or
// page.setRotationY(position * -30);
}
});
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter gridViewAdapter = new ImageAdapter(this);
gridViewAdapter.getItemId(position);
}
private class SliderAdapter extends PagerAdapter {
private Context context;
private LayoutInflater inflater;
public SliderAdapter(Context context) {
this.context = context;
}
int[] mThumbIds={ R.drawable.ferari, R.drawable.models,
R.drawable.ferrarihd,
R.drawable.ferrari,
R.drawable.yellowferrariiii,
R.drawable.models,
R.drawable.home,
R.drawable.carfront,
R.drawable.villa,
R.drawable.derrarii,
R.drawable.laferrari,
R.drawable.realestate,
R.drawable.carfront,R.drawable.california,R.drawable.laferrari
};
#Override
public CharSequence getPageTitle (int position) {
return "Ferrari Cars";
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view==object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position) {
inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.item_slider,container,false);
ImageView imageView=view.findViewById(R.id.img_item);
imageView.setImageResource(mThumbIds[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ImageView)object);
}
}
}
Firstly you have the position of image in FullScreenActivity so only do one thing to scroll that image
slider.setCurrentItem(pos);
After
int position = i.getExtras().getInt("id");
And use TouchImageView for zoom
I'm trying to replace colors by images from Drawable in this code.
I found this tutorial on how we can make an auto images slider by using viewpager on Android Studio, but this code is to switch colors images how can I replace this colors by images?
Here is my SliderAdapter.java
public class SliderAdapter extends PagerAdapter {
private Context context;
private List<Integer> color;
private List<String> colorName;
public SliderAdapter(Context context, List<Integer> color, List<String> colorName) {
this.context = context;
this.color = color;
this.colorName = colorName;
}
#Override
public int getCount() {
return color.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_slider, null);
TextView textView = (TextView) view.findViewById(R.id.textView);
LinearLayout linearLayout = (LinearLayout)
view.findViewById(R.id.linearLayout);
textView.setText(colorName.get(position));
linearLayout.setBackgroundColor(color.get(position));
ViewPager viewPager = (ViewPager) container;
viewPager.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager viewPager = (ViewPager) container;
View view = (View) object;
viewPager.removeView(view);
}
}
here is my MainActivity
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
TabLayout indicator;
List<Integer> color;
List<String> colorName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
viewPager=(ViewPager)findViewById(R.layout.viewPager);
indicator=(TabLayout)findViewById(R.layout.indicator);
color = new ArrayList<>();
color.add(Color.RED);
color.add(Color.GREEN);
color.add(Color.BLUE);
colorName = new ArrayList<>();
colorName.add("RED");
colorName.add("GREEN");
colorName.add("BLUE");
viewPager.setAdapter(new SliderAdapterDemo(this, color, colorName));
indicator.setupWithViewPager(viewPager, true);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SliderTimer(), 4000, 6000);
}
private class SliderTimer extends TimerTask {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (viewPager.getCurrentItem() < color.size() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
My activity make up viewpager and fragment,but when I first enter it hasn't data,if I scroll the pager from one to four,and then scroll form four to two,this moment it will show data, and you continue scroll, the all data will show.I don't know why this is,can you help me ? The following is my code:
public class WatchVideosActivity extends FragmentActivity {
private TabPageIndicator mTabIndicator;
private ViewPager mViewPager;
private int mWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watch_videos);
getScreenWidth();
initView();
}
/**
* 获取屏幕的宽度
*/
private void getScreenWidth(){
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
mWidth = dm.widthPixels;
}
/**
* 初始化View
*/
private void initView(){
mTabIndicator = (TabPageIndicator)findViewById(R.id.tab_pager_indicator);
mViewPager = (ViewPager)findViewById(R.id.watch_video_viewpager);
mViewPager.setAdapter(new WatchVideoPagerAdapter(WatchVideosActivity.this,getSupportFragmentManager(),mWidth));
mTabIndicator.setViewPager(mViewPager);
}
}
public class WatchVideoPagerAdapter extends FragmentPagerAdapter{
public static final String[] title = new String[]{"期指在线","和讯座谈会","中国经济学人","中国分析师访谈"};
private Context mContext;
private int mWidth;
public WatchVideoPagerAdapter(Context context,FragmentManager fm,int width) {
super(fm);
this.mContext = context;
this.mWidth = width;
}
#Override
public int getCount() {
return title.length;
}
#Override
public Fragment getItem(int position) {
return new FragmentFactory(mContext,position,mWidth); //创建fragment
}
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
}
public class FragmentFactory extends Fragment {
private int position;
private ListView mWatchVideoList;
private Context mContext;
private int mWidth;
private Integer mPagerIndex = 1;
private Integer[] titleId = new Integer[] { 123817825, 180524655, 168567237, 182001231 };
private List<VideoEntity> newsPagerList = new ArrayList<VideoEntity>();
private VideoAdapter videoAdapter;
public FragmentFactory(Context context, int position, int width) {
super();
this.position = position;
this.mContext = context;
this.mWidth = width;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.watchvideo_fragment_view, container, false);
mWatchVideoList = (ListView) view.findViewById(R.id.watchvideo_list);
getData();
mWatchVideoList.setAdapter(videoAdapter);
return view;
}
private Handler mHandler = new Handler() {
#SuppressWarnings("unchecked")
public void handleMessage(android.os.Message msg) {
newsPagerList = (List<VideoEntity>) msg.obj;
videoAdapter = new VideoAdapter(mContext, mWatchVideoList, newsPagerList, mWidth);
videoAdapter.notifyDataSetChanged();
};
};
private void getData() {
OkHttpUtils.getInputStream("http://wapi.hexun.com/Api_videoList.cc?pid=" + titleId[position] + "&pc=20&pn=1",
mHandler, 0);
}
}
Do not instantiate VideoAdapter inside handleMessage() instead instantiate it for one time in onCreteView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.watchvideo_fragment_view, container, false);
mWatchVideoList = (ListView) view.findViewById(R.id.watchvideo_list);
newsPagerList=new ArrayList<VideoEntity>();
videoAdapter = new VideoAdapter(mContext, mWatchVideoList, newsPagerList, mWidth); ///Send empty list for the first time
mWatchVideoList.setAdapter(videoAdapter);
getData();
return view;
}
Make a method inside VideoAdapter
VideoAdapter{
public void addItems(ArrayList<VideoEntity> list){
newsPageList.addAll(list); ///newsPageList is your list used in Adapter
notifyDataSetChanged();
}
When you getting the data from Server then call the addItems() method of adapter which will notify your list and you will show your data.
private Handler mHandler = new Handler() {
#SuppressWarnings("unchecked")
public void handleMessage(android.os.Message msg) {
newsPagerList = (List<VideoEntity>) msg.obj;
videoAdapter.addItems(newsPagerList);
};
};
Hope this will help you.
your list's adapter is not same in mHandler.