Custom icon on Tabs - android

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! ;)

Related

Custom TabLayout start center

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.

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");

FragmentPagerAdapter + BaseAdapter + UIL not Updating

I am trying to setup a tab title strip using swipes to switch between the fragments as demoed in the documentation here. It works, up to a point. The gridview shows all the images as required however, both fragment 1 and fragment 2 are showing the same images. It appears that fragment 2 is overwriting the images because if you click on the image in fragment 1, the fragment 1 details screen pops up (even though it shows an image from fragment 2).
Basically, I need my ImageAdapter (BaseAdapter) to show the correct images for each separate fragment. I don't see how the second fragment is interacting with the first if there are no static elements.
Edit: I tried changing to Picasso and the same error occurred so there has to be something in my code.
Edit2: I found this answer and it does let me redraw the grid when a fragment becomes visible but that causes a noticeable flicker and it is obvious the images were wrong. The problem has to lie somwhere with UIL/Picasso thinking the gridview in the separate fragments are the same object (they do have the same images but in different orders).
public void setupFragmentSwipes() {
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getFragmentManager());
mViewPager = (ViewPager) mRootView.findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
String[] array = getResources().getStringArray(R.array.SortOptions);
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new FragmentGrid();
Bundle args = new Bundle();
args.putInt("mMode", mMode);
args.putInt("mSortAorD", mSortAorD);
args.putInt("mSortType", i);
fragment.setArguments(args);
return fragment
}
#Override
public int getCount() {
return array.length;
}
#Override
public CharSequence getPageTitle(int position) {
return array[position];
}
}
FragmentGrid
public class FragmentGrid extends Fragment {
public int mode;
private ArrayList<Theme> mThemes;
private GridView listView;
private static DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
protected int mSavedPosition;
private int sortType;
private int sortAorD;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
mode = args.getInt("mMode", BaseConstants.ViewModes.NORMAL);
sortType = args.getInt("mSortType", BaseConstants.Sort.POPULAR);
sortAorD = args.getInt("mSortAorD", BaseConstants.Sort.DESC);
listView = (GridView) rootView.findViewById(R.id.gridview2);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_error)
.showImageOnFail(R.drawable.ic_error)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
return rootView;
}
#Override
public void onResume() {
super.onResume();
listView.setSelection(mSavedPosition);
ThemeManager tm = new ThemeManager(getActivity().getApplicationContext());
mThemes = tm.getModifiedThemeList(mode);
mThemes = tm.compare(sortType, sortAorD, checkIfTesting());
listView.setAdapter(new ImageAdapter(mThemes));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSavedPosition = position;
Intent intent = new Intent(getActivity(), ImagePagerActivity.class);
intent.putExtra("mMode", mode);
intent.putExtra("mSortAorD", sortAorD);
intent.putExtra("mSortType", sortType);
intent.putExtra("mPosition", position);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
ArrayList<Theme> imageAdapterThemeList;
public ImageAdapter(ArrayList<Theme> themes) {
imageAdapterThemeList = themes;
}
#Override
public int getCount() {
int result = 0;
if (imageAdapterThemeList != null) {
result = imageAdapterThemeList.size();
}
return result;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getActivity().getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
} else {
imageView = (ImageView) convertView;
}
Theme theme = imageAdapterThemeList.get(position);
imageLoader.displayImage(theme.getImageURL(), imageView, options);
return imageView;
}
}
fragment_collection_object.xml
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:horizontalSpacing="4dip"
android:numColumns="auto_fit"
android:columnWidth="150dip"
android:scrollbars="vertical"
android:stretchMode="columnWidth"
android:verticalSpacing="4dip"
android:padding="4dip" />
The only difference between your two fragment instances is that you have mSortType in your arguments Bundle set to 0 or 1 based on the page. You only use that to set up mThemes, which you never seem to use in your ImageAdapter.
So, if you are expecting your two ImageAdapter instances to return separate results, you need to either have it pay attention to mSortType or otherwise have it vary based on the page.
I encountered a problem that sounds very similar to this a while ago. It turned out to be the animations used when swapping pages and nothing to do with the pager or adapter at all. Essentially the animation resulted in fragment1 being on top of the fragment2 but completely transparent, so the user thought they were touching fragment2, but the events were received by fragment1..which makes it behave very much like the adapter was returning the wrong fragment...
In short, if you are using animations (particularly z-order altering animations) try disabling them and see if the problem goes away. If it does, you have a problem in your animations.
Hope that helps,
Good Luck.
Ok, I found the answer but I don't know why. I had to change the following from:
ArrayList<Theme> imageAdapterThemeList;
public ImageAdapter(ArrayList<Theme> themes) {
imageAdapterThemeList = themes;
}
to:
ArrayList<Theme> imageAdapterThemeList = new ArrayList<Theme>();
public ImageAdapter(ArrayList<Theme> themes) {
for (int i = 0; i< themes.size() ;i++) {
imageAdapterThemeList.add(i, themes.get(i));
}
}
I think, rather than creating a new ArrayList I was merely pointing to the old one. This new method actually recreates it but I'm sure it's not very efficient.

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;
}
}

How Do Implement ViewPager PagerTitleStrip?

I am a noob to android and i have been using tutorials to construct a viewpager layout. However, i have not been able to find a tutorial that also shows how to implement the pagertitle strip as well. I have been able to gather bits and pieces and have the bar displaying, but I don't know how make the text display properly. Currently it shows multiple titles at once and loses sync with the pages. Any help is greatly appreciated.
public class MyPagerActivity extends Activity {
PagerTitleStrip mTitleStrip;
String myTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mypagermain);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(2);
mTitleStrip = (PagerTitleStrip) findViewById(R.id.title_strip);
//some code
}
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 5;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.news;
view = inflater.inflate(resId, null);
LinearLayout layout0=(LinearLayout)view.findViewById(R.id.LLnews);
WebView newsfeed = (WebView) view.findViewById(R.id.webViewnews);
((ViewPager) collection).addView(view, 0);
return view;
case 1:
resId = R.layout.coinshows;
view = inflater.inflate(resId, null);
LinearLayout layout1=(LinearLayout)view.findViewById(R.id.LLcoinshows);
WebView coinshows = (WebView) view.findViewById(R.id.webViewcoinshows);
((ViewPager) collection).addView(view, 0);
return view;
}
return resId;
}
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return myTitle;
}
}
I recommend using PagerSlidingTabStrip. It's usage is very simple and the it emulates Play Store look&feel, very nice.
Usage
1.For a working implementation of this project see the sample/ folder.
Include the PagerSlidingTabStrip widget in your view. This should
usually be placed adjacent to the ViewPager it represents.
<com.astuetz.viewpager.extensions.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
2.In your onCreate method (or onCreateView for a fragment), bind the widget to the ViewPager.
// Set the pager with an adapter
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new TestAdapter(getSupportFragmentManager()));
// Bind the widget to the adapter
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
3.(Optional) If you use an OnPageChangeListener with your view pager you should set it in the widget rather than on the pager directly.
// continued from above
tabs.setOnPageChangeListener(mPageChangeListener);

Categories

Resources