Custom TabLayout start center - android

I want to make custom TabLayout. When activity created, first tab must center start. And second tabs first 3 letter shown in design.
after scrolling tabs, it must looks like this:
i try lots of code for make this however when i install app other phone padding change normally and design not work. How can i do this? Thanks a lot.

Use PagerTabStrip in the ViewPager
Here is my picture.
You can do like this.
xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<android.support.v4.view.PagerTabStrip
android:id="#+id/pagertab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#color/colorPrimary"
android:paddingBottom="20dp"
android:paddingTop="20dp"/>
</android.support.v4.view.ViewPager>
</RelativeLayout>
Activity code
public class MainActivity extends AppCompatActivity {
// layouts below the Tab
private View view1, view2, view3;
private List<View> viewList;
private ViewPager viewPager;
private PagerTabStrip mPagerTabStrip;
private List<String> titleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initTitle();
PagerAdapter pagerAdapter = getAdapter();
viewPager.setAdapter(pagerAdapter);
}
/**
* init view
*/
private void initView() {
viewPager = (ViewPager) findViewById(R.id.viewpager);
mPagerTabStrip = (PagerTabStrip) findViewById(R.id.pagertab);
// Tab Indicator Color setting
mPagerTabStrip.setTabIndicatorColorResource(R.color.colorAccent);
LayoutInflater inflater = getLayoutInflater();
view1 = inflater.inflate(R.layout.layout1, null);
view2 = inflater.inflate(R.layout.layout2, null);
view3 = inflater.inflate(R.layout.layout3, null);
// Add view to the viewList
viewList = new ArrayList<View>();
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
}
/**
* add title to the titleList
*/
private void initTitle() {
titleList = new ArrayList<String>();
titleList.add("January, 2017");
titleList.add("February, 2017");
titleList.add("July, 2017");
}
#NonNull
private PagerAdapter getAdapter() {
return new PagerAdapter() {
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == viewList.get((int) Integer.parseInt(arg1.toString()));
}
#Override
public int getCount() {
return viewList.size();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(viewList.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(viewList.get(position));
return position;
}
/**
* title
* #param pos
* #return
*/
#Override
public CharSequence getPageTitle(int pos) {
// title icon setting ,space added before text for
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(" " + titleList.get(pos)); //
Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
// text color setting
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.WHITE);
// icon setting
// ssb.setSpan(span, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// text color setting
spannableStringBuilder.setSpan(fcs, 1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.setSpan(new RelativeSizeSpan(1.2f), 1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableStringBuilder;
}
};
}
}
You need to know about setTabIndicatorColorResource and getPageTitle in the PagerAdapter, and these are more important.

Related

scroll image that has text description using view pager in android

My current design lets me swipe (left and right swipe) through images like this:current design
But what I really want to do is change it a bit so that I have a text description at the bottom. The text description changes when the image change. The new design is like this:
new design
I'm not sure how do I achieved this design? For example how do I draw those three circles? How do I make the text change when the image changed? Can anyone please advise?
Here is my code:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.chiang_mai,
R.drawable.himeji,
R.drawable.petronas_twin_tower,
R.drawable.ulm
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
//activity_main
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Oh, you need to inflate a custom layout containing an ImageView and a TextView below it (or any other arrangement you may need). Then modify your PagerAdapter to inflate this custom layout with the image and the text. This is just to give you a better idea.
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = container.getContext(); // I feel this is a better implementation
CustomLayout layout = new CustomLayout(context);
// This is a custom layout that you could create
// you could init a LinearLayout and add an
// ImageView and a TextView to it, your call :)
// Set image and text in your view accortind to 'position'
return layout;
}
As i understand, you want both image and text to be scrolled, and you need indicator at the bottom.
So you change your PagerAdapter to sth like this:
public class ImagePagerAdapter extends PagerAdapter {
private int[] mImages ;
private Context mContext;
public ImagePagerAdapter(Context context, int[] mImages) {
mContext = context;
this.mImages = mImages;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.your_layout_with_image_and_text,container,false);
ImageView imageView = (ImageView) layout.findViewById(R.id.your_image_view);
TextView textView=(TextView)layout.findViewById(R.id.your_text_view)
//.. load image and text you got from constructor
container.addView(layout, 0);
return layout;
}
public int getCount() {
if(mImages!=null)
return mImages.length;
else
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
}
For indicator, use this and put it below ViewPager in xml
<your_package.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:fillColor="#color/primary_color"
app:pageColor="#color/white"
app:strokeColor="#color/primary_color"
android:padding="4dp" />
Try this way,you need to create array for texts,
private int imageArr[] = { R.drawable.f, R.drawable.g, R.drawable.h,
R.drawable.i, R.drawable.j};
private String[] stringArray = new String[] { "first", "sec","third","fourth","fifth"};
initialize your adapter
adapter = new ImagePagerAdapter(this, imageArr, stringArray );
make your adapter like
int imgArray [];
String[] stringArray;
public ImagePagerAdapter(Activity act, int[] imgArra, String[] stringArr) {
activity = act;
imgArray = imgArra;
stringArray = stringArr;
}
then get the position
txt.setText(stringArray[position]);
See this for more

Custom icon on Tabs

I am using PagerSlidingTabStrip with a ViewPager.
Is there a way I can change the Tab icons dynamically, depending on some actions. Like when a notification is received, I want to change the icon on notifications tab to show how many notifications are unread.
Or any other library which would support that without much tweaking.
You can do it by implementing PagerSlidingTabStrip.CustomTabProvider interface. I made example project for your case, so let's explore it step by step.
Firstly, create a layout for our tab called tab_layout, for example. It will contain 2 TextView's for title and badge. In my case it looks like:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tab_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="16sp"
android:singleLine="true" />
<TextView
android:id="#+id/badge"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_toRightOf="#+id/tab_title"
android:textSize="12sp"
android:gravity="center"
android:layout_marginLeft="8dp"
android:layout_centerVertical="true"
android:textColor="#android:color/white"
android:background="#drawable/badge_background" />
</RelativeLayout>
Secondly, create a simple model for Tab, that will containt a tab title and number of notifications. I've called it ViewPagerTab:
public class ViewPagerTab {
public String title;
public int notifications;
public ViewPagerTab(String title, int notifications) {
this.title = title;
this.notifications = notifications;
}
}
Thirdly, implement PagerSlidingTabStrip.CustomTabProvider interface on your FragmentPagerAdapter. Here we will inflate tab layout and initialize the tab views, also we will define fragments for positions:
public class MainAdapter extends FragmentPagerAdapter
implements PagerSlidingTabStrip.CustomTabProvider {
ArrayList<ViewPagerTab> tabs;
public MainAdapter(FragmentManager fm, ArrayList<ViewPagerTab> tabs) {
super(fm);
this.tabs = tabs;
}
#Override
public View getCustomTabView(ViewGroup viewGroup, int i) {
RelativeLayout tabLayout = (RelativeLayout)
LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.tab_layout, null);
TextView tabTitle = (TextView) tabLayout.findViewById(R.id.tab_title);
TextView badge = (TextView) tabLayout.findViewById(R.id.badge);
ViewPagerTab tab = tabs.get(i);
tabTitle.setText(tab.title.toUpperCase());
if (tab.notifications > 0) {
badge.setVisibility(View.VISIBLE);
badge.setText(String.valueOf(tab.notifications));
} else {
badge.setVisibility(View.GONE);
}
return tabLayout;
}
#Override
public void tabSelected(View view) {
//if you don't want badges disappear when you select tab comment next lines
RelativeLayout tabLayout = (RelativeLayout) view;
TextView badge = (TextView) tabLayout.findViewById(R.id.badge);
badge.setVisibility(View.GONE);
}
#Override
public void tabUnselected(View view) {
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new OneFragment();
case 1:
return new TwoFragment();
case 2:
return new ThreeFragment();
}
return new OneFragment();
}
#Override
public int getCount() {
return tabs.size();
}
}
Fourthly, initialize tabs and pager in MainActivity's onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
ArrayList<ViewPagerTab> tabsList = new ArrayList<>();
tabsList.add(new ViewPagerTab("One", 0));
tabsList.add(new ViewPagerTab("Two", 1));
tabsList.add(new ViewPagerTab("Three", 2));
adapter = new MainAdapter(getSupportFragmentManager(), tabsList);
pager.setAdapter(adapter);
tabs.setViewPager(pager);
pager.setOffscreenPageLimit(3);
getSupportActionBar().hide();
}
You will get something like this:
And finally, to get and change tab views in runtime, you can simply call getChildAt function of PagerSlidingTabStrip object in your Activity or Fragment, and do what you want:
private void notifyTabStripChanged(int position, int notificationsCount) {
LinearLayout tabHost = (LinearLayout) tabs.getChildAt(0);
RelativeLayout tabLayout = (RelativeLayout) tabHost.getChildAt(position);
TextView badge = (TextView) tabLayout.findViewById(R.id.badge);
if (notificationsCount > 0) {
badge.setVisibility(View.VISIBLE);
badge.setText(String.valueOf(notificationsCount));
} else {
badge.setVisibility(View.GONE);
}
}
Don't forget, that child views count is starting from 0. If you want to use images, just replace ImageView with TextView badge and change it's image resource instead of text. Enjoy!
You can achieve what you want by forking this lib and change the behaviour of IconTabProvider used there in sample app implemented to use only static resources.
Changes to do to your lib fork to add dynamic icon changes:
In PagerSlidingTabStrip:
Change return type (and name) of getPageIconResId method of IconTabProvider interface
public interface IconTabProvider {
//public int getPageIconResId(int position) becomes
public Bitmap getPageIconBitmap(int position)
}
This causes to update the call to this method in PagerSlidingTabStrip
--
And also to change the method addIconTab from
private void addIconTab(final int position, int resId) {
ImageButton tab = new ImageButton(getContext());
tab.setImageResource(resId);
addTab(position, tab);
}
to
private void addIconTab(final int position, bitmap icon) {
ImageButton tab = new ImageButton(getContext());
tab.setImageBitmap(icon);
addTab(position, tab);
}
Then you need to create an adapter for your tabs bar, here is an example:
public class DynamicIconPagerAdapter extends PagerAdapter implements IconTabProvider {
public HashMap<Integer, Bitmap> mapBetweenPositionAndIcons = new HashMap();
public DynamicIconPagerAdapter () {
super();
}
#Override
public int getCount() {
return mapBetweenPositionAndIcons.size();
}
#Override
public Bitmap getPageIconResId(int position) {
return mapBetweenPositionAndIcons.get(position);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// looks a little bit messy here
TextView v = new TextView(getActivity());
v.setBackgroundResource(R.color.background_window);
v.setText("PAGE " + (position + 1));
final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources()
.getDisplayMetrics());
v.setPadding(padding, padding, padding, padding);
v.setGravity(Gravity.CENTER);
container.addView(v, 0);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object view) {
container.removeView((View) view);
}
#Override
public boolean isViewFromObject(View v, Object o) {
return v == ((View) o);
}
}
Finally, when you want to update an icon just change the corresponding bitmap of the map (mapBetweenPositionAndIcons) and call notifyDataSetChanged() on your PagerSlidingTabStrip object.
I havn't tested my solution yet due to a lack of time, but I will as soon as possible! ;)

Viewpager slide next page lags

I've a gridview with clickable items. When I click on an item the gridview is became hidden and I show a ViewPager.
In my case this ViewPager should work like slideshow.
So I've tried to follow the Google example here: http://developer.android.com/training/animation/screen-slide.html
If I open a new activity on gridview item click, the viewpager is working well (like the Google example). But if I open the ViewPager hiding the gridview the slide animation become lagging.
Obviously I've tried to open the viewpager with same graphics/bitmaps etc..
Unfortunately my application need to work in the same activity, and I cannot open a new one.
Is there some limitations about ViewPager? Or I should give attention on something particular?
Quite Simple.
Unfortunately my application need to work in the same activity, and I cannot open a new one.
I presume when a user click one of the grid view of the item (maybe containing image), a view pagers shows up with the image and the user can slide the ViewPager for next image and so on.
In this case, use a Dialog Fragment.
Layout for ViewPager's Image :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black">
<ImageView
android:id="#+id/image_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:scaleType="fitCenter" />
</RelativeLayout>
Dialog Fragment Code :
public class SlideshowDialogFragment extends DialogFragment {
private String TAG = SlideshowDialogFragment.class.getSimpleName();
private ArrayList<Image> images;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private TextView lblCount, lblTitle, lblDate;
private int selectedPosition = 0;
static SlideshowDialogFragment newInstance() {
SlideshowDialogFragment f = new SlideshowDialogFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_image_slider, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
lblCount = (TextView) v.findViewById(R.id.lbl_count);
lblTitle = (TextView) v.findViewById(R.id.title);
lblDate = (TextView) v.findViewById(R.id.date);
images = (ArrayList<Image>) getArguments().getSerializable("images");
selectedPosition = getArguments().getInt("position");
Log.e(TAG, "position: " + selectedPosition);
Log.e(TAG, "images size: " + images.size());
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
setCurrentItem(selectedPosition);
return v;
}
private void setCurrentItem(int position) {
viewPager.setCurrentItem(position, false);
displayMetaInfo(selectedPosition);
}
// page change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
displayMetaInfo(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void displayMetaInfo(int position) {
lblCount.setText((position + 1) + " of " + images.size());
Image image = images.get(position);
lblTitle.setText(image.getName());
lblDate.setText(image.getTimestamp());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
}
// adapter
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);
ImageView imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);
Image image = images.get(position);
Glide.with(getActivity()).load(image.getLarge())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageViewPreview);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
Send the image link and its description/ title through this code:
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
The array List being used :
private ArrayList<Image> images = new ArrayList<>();
Image image = new Image();
image.setName("Image Title");
image.setLarge("ImageUrl");

Gallery type scroll view in android

I am trying to implement a scroller like show in the image below.
I have tried using viewpager but it only shows one item at a time. And I need to show 5 of them and of different sizes. The one in middle needs to be bigger.
Each Item is a frameLayout that contains an ImageView and a TexView, I dont have any problem implementing that part. The problem is it needs to be a scroller and have many items in scroller e.g upto 15 maybe. But should have only 5 items visible at any one time just like shown below. I have tried many implementations. Please some one give me a working example as I have already tried many examples none of them works perfectly. I have waisted more than a week on this one.
You can control it by overriding getPageWidth() in the PagerFragmentAdapter:
#Override
public float getPageWidth(int position) {
return(0.4f);
}
and making sure the size of your images is not too large, so that the page width fits multiple images.
Here are all the steps to set this up:
1) Add a fragment container to your activity layout, where you will load the PhotoPagerFragment:
<!-- PHOTO PAGER FRAGMENT -->
<FrameLayout
android:id="#+id/photoPagerFragmentContainer"
android:layout_width="match_parent"
android:layout_height="150dp"
android:tag="sticky"
android:layout_gravity="center_horizontal" >
</FrameLayout>
2) Inject the PhotoPagerFragment in your activity's onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
//Insert the fragment
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.photoPagerFragmentContainer);
if (fragment == null) {
fragment = new PhotoPagerFragment();
fm.beginTransaction()
.add(R.id.photoPagerFragmentContainer, fragment)
.commit();
}
}
3) Create a layout for your PhotoPagerFragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/photoPager"
android:layout_width="fill_parent"
android:layout_height="120dp"
android:layout_marginTop="2dp"/>
</LinearLayout>
4) Create your PhotoPagerFragment:
public class PhotoPagerFragment extends Fragment {
private ViewPager mPhotoPager;
private PagerAdapter mPhotoAdapter;
public static final String TAG = "PhotoPagerFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo_pager, container, false);
mPhotoAdapter = new PhotoPagerFragmentAdapter(getActivity().getSupportFragmentManager());
mPhotoPager = (ViewPager) view.findViewById(R.id.photoPager);
mPhotoPager.setAdapter(mPhotoAdapter);
return view;
}
}
5) And the adapter:
public class PhotoPagerFragmentAdapter extends FragmentPagerAdapter {
private int[] Images = new int[] {
R.drawable.photo_1, R.drawable.photo_2,
R.drawable.photo_3, R.drawable.photo_4,
R.drawable.photo_5, R.drawable.photo_6
};
private int mCount = Images.length;
public PhotoPagerFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PhotoDetailsFragment.newInstance(Images[position]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public float getPageWidth(int position) {
return(0.4f);
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
6) And finally, your PhotoDetailsFragment that will show each image:
public final class PhotoDetailsFragment extends Fragment {
private int photoResId;
private static final String TAG = "PhotoDetailsFragment";
public static final String EXTRA_PHOTO_ID = "com.sample.photo_res_id";
public static PhotoDetailsFragment newInstance(int photoResId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_PHOTO_ID, photoResId);
PhotoDetailsFragment fragment = new PhotoDetailsFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
photoResId = (Integer)getArguments().getSerializable(EXTRA_PHOTO_ID);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final ImageView image = new ImageView(getActivity());
image.setImageResource(photoResId);
// Hook up the clicks on the thumbnail views
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
}
});
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(-1, -1));
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}

Android Viewpager as Image Slide Gallery

I am using Jake's ViewPageIndicator and want to display Images like a swipe gallery.
Any refernce link where i can get started. I have implemented the basic viewpager and now want to implement image viewpaper as below
Is it possible to to achieve using ViewPageIndicator ?
In Jake's ViewPageIndicator he has implemented View pager to display a String array (i.e.
["this","is","a","text"]) which you pass from YourAdapter.java (that extends FragmentPagerAdapter) to the YourFragment.java which returns a View to the viewpager.
In order to display something different, you simply have to change the context type your passing. In this case you want to pass images instead of text, as shown in the sample below:
This is how you setup your Viewpager:
public class PlaceDetailsFragment extends SherlockFragment {
PlaceSlidesFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
public static final String TAG = "detailsFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_place_details,
container, false);
mAdapter = new PlaceSlidesFragmentAdapter(getActivity()
.getSupportFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
((CirclePageIndicator) mIndicator).setSnap(true);
mIndicator
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Toast.makeText(PlaceDetailsFragment.this.getActivity(),
"Changed to page " + position,
Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrolled(int position,
float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return view;
}
}
your_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip" />
</LinearLayout>
YourAdapter.java
public class PlaceSlidesFragmentAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
private int[] Images = new int[] { R.drawable.photo1, R.drawable.photo2,
R.drawable.photo3, R.drawable.photo4
};
protected static final int[] ICONS = new int[] { R.drawable.marker,
R.drawable.marker, R.drawable.marker, R.drawable.marker };
private int mCount = Images.length;
public PlaceSlidesFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new PlaceSlideFragment(Images[position]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
YourFragment.java
// you need to return image instaed of text from here.//
public final class PlaceSlideFragment extends Fragment {
int imageResourceId;
public PlaceSlideFragment(int i) {
imageResourceId = i;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
image.setImageResource(imageResourceId);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams());
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}
You should get a View pager like this from the above code.
I made a library named AndroidImageSlider, you can have a try.
Image Viewer with ViewPager Implementation, check this project https://github.com/chiuki/android-swipe-image-viewer
Refer this discussion also Swiping images (not layouts) with viewpager
Just use this https://gist.github.com/8cbe094bb7a783e37ad1 for make surrounding pages visible and http://viewpagerindicator.com/ this, for indicator. That's pretty cool, i'm using it for a gallery.
Hoho.. It should be very easy to use Gallery to implement this, using ViewPager is much harder. But i still encourage to use ViewPager since Gallery really have many problems and is deprecated since android 4.2.
In PagerAdapter there is a method getPageWidth() to control page size, but only by this you cannot achieve your target.
Try to read the following 2 articles for help.
multiple-view-viewpager-options
viewpager-container
you can use custom gallery control.. check this https://github.com/kilaka/ImageViewZoom
use galleryTouch class from this..
Hi if your are looking for simple android image sliding with circle indicator you can download the complete code from here http://javaant.com/viewpager-with-circle-indicator-in-android/#.VysQQRV96Hs . please check the live demo which will give the clear idea.
enter code here public Timer timer;
public TimerTask task;
public ImageView slidingimage;
private int[] IMAGE_IDS = {
R.drawable.home_banner1, R.drawable.home_banner2, R.drawable.home_banner3
};
enter code here #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 2000; // delay for 1 sec.
int period = 2000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
enter code here private void AnimateandSlideShow() {
slidingimage = (ImageView)findViewById(R.id.banner);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
slidingimage.startAnimation(rotateimage);
}
A great One Image slider : https://github.com/daimajia/AndroidImageSlider Check it

Categories

Resources