Android view pager with page indicator - android

I need to get page indicator in the view pager file with images. Here is my code.
public class IndicatorActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.pager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicat);
indicator.setViewPager( myPager );
}
}
In this code, i got an error in TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicat); as TitlePageIndicator cannot be resolved to a type. What is this error. How can I resolve it?
here is my xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<com.viewpagerindicator.TitlePageIndicator
android:id="#+id/indicat"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
</LinearLayout>
What code do I need to write in the TitlePageIndicator?
I want to do this without using fragments.
Me also created a class such as:
class MyPagerAdapter extends PagerAdapter {
private static Integer[] titles = new Integer[]
{
R.drawable.jk,R.drawable.lm,R.drawable.no
};
public int getCount() {
return 3;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
ImageView iv;
view = inflater.inflate(R.layout.first, null);
((ViewPager) collection).addView(view, 0);
switch (position) {
case 0:
iv = (ImageView)view.findViewById(R.id.imageView1);
iv.setImageResource(titles[position]);
break;
case 1:
iv = (ImageView)view.findViewById(R.id.imageView1);
iv.setImageResource(titles[position]);
break;
case 2:
iv = (ImageView)view.findViewById(R.id.imageView1);
iv.setImageResource(titles[position]);
break;
}
return view;
}
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
}
Did I want to do anything more than this class?
Thanks in advance for help

UPDATE: 22/03/2017
main fragment layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RadioGroup
android:id="#+id/page_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="#dimen/margin_help_container"
android:orientation="horizontal">
<RadioButton
android:id="#+id/page1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true" />
<RadioButton
android:id="#+id/page2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:id="#+id/page3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
</FrameLayout>
set up view and event on your fragment like this:
mViewPaper = (ViewPager) view.findViewById(R.id.viewpager);
mViewPaper.setAdapter(adapder);
mPageGroup = (RadioGroup) view.findViewById(R.id.page_group);
mPageGroup.setOnCheckedChangeListener(this);
mViewPaper.addOnPageChangeListener(this);
*************************************************
*************************************************
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// when current page change -> update radio button state
int radioButtonId = mPageGroup.getChildAt(position).getId();
mPageGroup.check(radioButtonId);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
// when checked radio button -> update current page
RadioButton checkedRadioButton = (RadioButton)radioGroup.findViewById(checkedId);
// get index of checked radio button
int index = radioGroup.indexOfChild(checkedRadioButton);
// update current page
mViewPaper.setCurrentItem(index), true);
}
custom checkbox state: Custom checkbox image android
Viewpager tutorial: http://architects.dzone.com/articles/android-tutorial-using

Here are a few things you need to do:
1-Download the library if you haven't already done that.
2- Import into Eclipse.
3- Set you project to use the library:
Project-> Properties -> Android -> Scroll down to Library section, click Add... and select viewpagerindicator.
4- Now you should be able to import com.viewpagerindicator.TitlePageIndicator.
Now about implementing this without using fragments:
In the sample that comes with viewpagerindicatior, you can see that the library is being used with a ViewPager which has a FragmentPagerAdapter.
But in fact the library itself is Fragment independant. It just needs a ViewPager.
So just use a PagerAdapter instead of a FragmentPagerAdapter and you're good to go.

I know this has already been answered, but for anybody looking for a simple, no-frills implementation of a ViewPager indicator, I've implemented one that I've open sourced. For anyone finding Jake Wharton's version a bit complex for their needs, have a look at https://github.com/jarrodrobins/SimpleViewPagerIndicator.

I have also used the SimpleViewPagerIndicator from #JROD. It also crashes as described by #manuelJ.
According to his documentation:
SimpleViewPagerIndicator pageIndicator = (SimpleViewPagerIndicator) findViewById(R.id.page_indicator);
pageIndicator.setViewPager(pager);
Make sure you add this line as well:
pageIndicator.notifyDataSetChanged();
It crashes with an array out of bounds exception because the SimpleViewPagerIndicator is not getting instantiated properly and the items are empty. Calling the notifyDataSetChanged results in all the values being set properly or rather reset properly.

Just an improvement to the nice answer given by #vuhung3990.
I implemented the solution and works great but if I touch one radio button it will be selected and nothing happens.
I suggest to also change page when a radio button is tapped. To do this, simply add a listener to the radioGroup:
mPager = (ViewPager) findViewById(R.id.pager);
final RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radiogroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radioButton :
mPager.setCurrentItem(0, true);
break;
case R.id.radioButton2 :
mPager.setCurrentItem(1, true);
break;
case R.id.radioButton3 :
mPager.setCurrentItem(2, true);
break;
}
}
});

you have to do following:
1-Download the full project from here https://github.com/JakeWharton/ViewPagerIndicator
ViewPager Indicator
2- Import into the Eclipse.
After importing if you want to make following type of screen then follow below steps -
change in
Sample circles Default
package com.viewpagerindicator.sample;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.CirclePageIndicator;
public class SampleCirclesDefault extends BaseSampleActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_circles);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
// mPager.setAdapter(mAdapter);
ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
mPager.setAdapter(adapter);
mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
}
ImageAdapter
package com.viewpagerindicator.sample;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAdapter extends PagerAdapter {
private Context mContext;
private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
R.drawable.about3, R.drawable.about4, R.drawable.about5,
R.drawable.about6, R.drawable.about7
};
public ImageAdapter(Context context) {
mContext = context;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
LayoutInflater inflater = (LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.gallery_view, null);
ImageView view_image = (ImageView) convertView
.findViewById(R.id.view_image);
TextView description = (TextView) convertView
.findViewById(R.id.description);
view_image.setImageResource(mImageIds[position]);
view_image.setScaleType(ImageView.ScaleType.FIT_XY);
description.setText("The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
+ "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
+ "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");
((ViewPager) container).addView(convertView, 0);
return convertView;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ViewGroup) object);
}
}
gallery_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/about_bg"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/about_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="#+id/about_layout1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".4"
android:orientation="vertical" >
<ImageView
android:id="#+id/view_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/about1">
</ImageView>
</LinearLayout>
<LinearLayout
android:id="#+id/about_layout2"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight=".6"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
android:textColor="#000000"
android:gravity="center"
android:padding="18dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearance" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:fillViewport="false"
android:orientation="vertical"
android:scrollbars="none"
android:layout_marginBottom="10dp"
android:padding="10dp" >
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#000000"
android:text="TextView" />
</ScrollView>
</LinearLayout>
</LinearLayout>

You Can create a Linear layout containing an array of TextView (mDots).
To represent the textView as Dots provide this HTML source in your code .
refer my code .
I got this information from Youtube Channel TVAC Studio .
here the code : `
addDotsIndicator(0);
viewPager.addOnPageChangeListener(viewListener);
}
public void addDotsIndicator(int position)
{
mDots = new TextView[5];
mDotLayout.removeAllViews();
for (int i = 0; i<mDots.length ; i++)
{
mDots[i]=new TextView(this);
mDots[i].setText(Html.fromHtml("•")); //HTML for dots
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorAccent));
mDotLayout.addView(mDots[i]);
}
if(mDots.length>0)
{
mDots[position].setTextColor(getResources().getColor(R.color.orange));
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addDotsIndicator(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};`

Related

PagerAdapter change TextView when swiping

I'm using a PagerAdapter to swipe through a couple of ImageViews which works perfectly fine. I have a bunch of people in the gallery and I wish to add an individual name/description (id: speaker_name) to them. All I got to work is the same description for all of them. Im absolutely new to this and I am struggling for a day now to get it to work. All the solutions I found used fragments or an OnPageChangeListener but i couldnt figure out how to implement it.
This is what i've got:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/basicBackground">
</android.support.v4.view.ViewPager>
<TextView
android:id="#+id/speaker_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50sp"
android:text="The Name"
android:textAlignment="center"
android:textColor="#android:color/white"
android:textSize="30sp" />
</FrameLayout>
</RelativeLayout>`
PagerAdapter:
public class ImageAdapter extends PagerAdapter {
SpeakerActivity sa;
Context context;
int i = 0;
public int[] GalImages = new int[] {
R.drawable.ben,
R.drawable.brett,
R.drawable.mark,
R.drawable.dusan,
R.drawable.michael,
R.drawable.mike,
R.drawable.ollie,
R.drawable.rebecca,
R.drawable.sebastian,
R.drawable.thomas,
R.drawable.tomasz,
R.drawable.toni,
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
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(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Activity:
public class SpeakerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speaker_activity);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
}
To change textview text when swiping you can do this inside oncreate() method:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position){
case 0:
//Do stuff
textview.setText("Ben");
break;
case 1:
//Do stuff
textview.setText("Brett");
break;
//Add other cases for the pages
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
This is the implementation of viewpager OnPageChangeListener() for me the best way.
let me give you the basic idea
ViewPager that the Activity layout is binded to.
ImageAdapter that extends ViewPager/FragmentPager that basically adds views or fragments into the viewpager so that the activity can show it to you.
the activity connects the two objects by setting the viewpager's adapter to your ImageAdapter
Like I said in #2 there are many ways you u can implement the ViewPager there are many sites out there.
refer to https://www.bignerdranch.com/
it explain in great detail

ViewPager with items preview

I want to show a ViewPager with all the days of the week with a preview of the following and previous item of the current one.
I've tried a lot of solutions suggested from stackoverflow but none of them is working. I don't wont to use fragments in the ViewPager so I've used a PagerAdapter.
See this image:
My starting point is:
activity_main.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Choose a day of the week:" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/weekOfTheDayPager"/>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpAdapter();
}
private void setUpAdapter() {
ViewPager _mViewPager = (ViewPager) findViewById(R.id.weekOfTheDayPager);
final String[] daysOfTheWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
final Context myContext = getBaseContext();
_mViewPager.setAdapter(new PagerAdapter() {
#Override
public int getCount() {
return daysOfTheWeek.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = LayoutInflater.from(myContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.dayoftheweeklayout, collection, false);
((TextView) layout.findViewById(R.id.dayOfTheWeekTextView)).setText(daysOfTheWeek[position]);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
});
}}
and finally the layout for the ViewPager item:
dayoftheweeklayout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dayOfTheWeekTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Sunday"
android:layout_gravity="center_horizontal"/>
</FrameLayout>
Any suggestion will be appreciated.
So it looks like you want a carousel view.
Here's the recipe:
First, in order to show pages to the side in ViewPager, you need to provide some padding on the sides and then set clipToPadding to false:
<android.support.v4.view.ViewPager
android:id="#+id/weekOfTheDayPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:paddingEnd="#dimen/view_pager_padding"
android:paddingLeft="#dimen/view_pager_padding"
android:paddingRight="#dimen/view_pager_padding"
android:paddingStart="#dimen/view_pager_padding"/>
Next, you need to override getPageWidth in your PagerAdapter to tell the ViewPager that you want to display three pages at a time:
#Override
public float getPageWidth(int position) {
return 1F / 3F;
}
Then you need to tell the ViewPager to use a custom PageTransformer:
viewPager.setPageTransformer(false, new MyPageTransformer());
...
public static class MyPageTransformer implements ViewPager.PageTransformer {
private ArgbEvaluator mColorFade = new ArgbEvaluator();
#Override
public void transformPage(View page, float position) {
// position is 0 when page is centered (current)
// -1 when page is all the way to the left
// +1 when page is all the way to right
// Here's an example of how you might morph the color
int color = mColorFade(Math.abs(position), Color.RED, Color.GRAY);
TextView tv = (TextView) page.findViewById(R.id.dayOfTheWeekTextView);
tv.setTextColor(color);
}
}
There's probably something I forgot, but search SO for "android viewpager carousel" and you will find an answer in there somewhere.

Android viewPager image slide right to left

I want to add an image slide. But cannot make it slide from right to left. (for languages like Arabic or Hebrew)
I checked nearly all replies in stackoverflow, but can not find a clear solution.
I write here the whole code.
Please write me clearly, I am not a professional
mainActivity;
package com.manishkpr.viewpagerimagegallery;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
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);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
}
here
is
the
ImageAdapter.java;
package com.manishkpr.viewpagerimagegallery;
import android.content.Context;
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 ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
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(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
and here is the layout file;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Create a Layout file pager_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView" />
</LinearLayout>
Change your PagerAdapter like this:
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
LayoutInflater mLayoutInflater;
ImageAdapter(Context context){
this.context=context;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(GalImages[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
EDIT 1:
A trick :
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);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(adapter.getCount()-1);
}
I hope this helps :)
ViewPager is not support RTL.
You have to create custom ViewPager for swipe Right To Left for Arabic and other languages.
If you don't want to make code then there are lots of library available you can use one of them.
1. RtlViewPager
2. RtlViewPager
Instead of using ViewPager I suggest you to use SwipeDeck Because as Niranj Patel said ViewPager does not Support Right to left.
<?xml version="1.0" encoding="utf-8"?>
<com.daprlabs.cardstack.SwipeFrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipedeck="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.daprlabs.cardstack.SwipeDeck
android:id="#+id/swipe_deck"
android:layout_width="match_parent"
android:layout_height="480dp"
android:padding="20dp"
swipedeck:card_spacing="10dp"
swipedeck:max_visible="3"
swipedeck:render_above="true"
swipedeck:rotation_degrees="15" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="Button" />
</com.daprlabs.cardstack.SwipeFrameLayout>
Just smiple solution but it is not professional
Write this in xml for VeiwPager
android:rotationY="180"
and also in veiw_item
android:rotationY="180".
ViewPager2 supports RTL paging.
From docs:
RTL paging is enabled automatically where appropriate based on locale, but you can also manually enable RTL paging for a ViewPager2 element by setting its android:layoutDirection attribute:
<androidx.viewpager2.widget.ViewPager2
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layoutDirection="rtl" />

swipe view pager with indicator

I am having a swipe ViewPager with page indicator but when I run my application I see the playbutton.xml and the swipe view does not work.
Here is my java Activity (play_button.java):
public class play_button extends Activity implements
ViewPager.OnPageChangeListener, View.OnClickListener{
protected View view;
private ImageButton btnNext, btnFinish;
private ViewPager intro_images;
private LinearLayout pager_indicator;
private int dotsCount;
private ImageView[] dots;
private ViewPagerAdapter mAdapter;
private int[] mImageResources = {
R.mipmap.abc1,
R.mipmap.abc2,
R.mipmap.abc3,
R.mipmap.abc4,
R.mipmap.abc5
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
// To make activity full screen.
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setReference();
setContentView(R.layout.playbutton);
/* toolbar.setVisibility(View.GONE);*/
}
public void setReference() {
view = LayoutInflater.from(this).inflate(R.layout.playbutton,null);
intro_images = (ViewPager) view.findViewById(R.id.pager_introduction);
btnNext = (ImageButton) view.findViewById(R.id.btn_next);
btnFinish = (ImageButton) view.findViewById(R.id.btn_finish);
pager_indicator = (LinearLayout) view.findViewById(R.id.viewPagerCountDots);
btnNext.setOnClickListener(this);
btnFinish.setOnClickListener(this);
mAdapter = new ViewPagerAdapter(play_button.this, mImageResources);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(0);
intro_images.addOnPageChangeListener(this);
setUiPageViewController();
}
private void setUiPageViewController() {
dotsCount = mAdapter.getCount();
dots = new ImageView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.nonselecteditem_dot, null));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
dots[0].setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.selecteditem_dot, null));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_next:
intro_images.setCurrentItem((intro_images.getCurrentItem() < dotsCount)
? intro_images.getCurrentItem() + 1 : 0);
break;
case R.id.btn_finish:
finish();
break;
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.nonselecteditem_dot, null));
}
dots[position].setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.selecteditem_dot, null));
if (position + 1 == dotsCount) {
btnNext.setVisibility(View.GONE);
btnFinish.setVisibility(View.VISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnFinish.setVisibility(View.GONE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
Here is my xml (playbutton.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"
android:fitsSystemWindows="true"
tools:context="com.androprogrammer.tutorials.samples.ViewPagerDemo">
<android.support.v4.view.ViewPager
android:id="#+id/pager_introduction"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:listitem="#layout/pager_item" />
<RelativeLayout
android:id="#+id/viewPagerIndicator"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
android:layout_marginTop="5dp"
android:gravity="center">
<LinearLayout
android:id="#+id/viewPagerCountDots"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:gravity="center"
android:orientation="horizontal" />
<ImageButton
android:id="#+id/btn_next"
android:layout_width="42dip"
android:layout_height="42dip"
android:layout_alignParentRight="true"
android:layout_marginRight="15dip"
android:background="#drawable/btn_round_semitransperant"
android:src="#mipmap/ic_navigation_arrow_forward" />
<ImageButton
android:id="#+id/btn_finish"
android:layout_width="42dip"
android:layout_height="42dip"
android:layout_alignParentRight="true"
android:layout_marginRight="15dip"
android:background="#drawable/btn_round_semitransperant"
android:contentDescription="Let's start"
android:src="#mipmap/ic_navigation_check"
android:visibility="gone" />
</RelativeLayout>
Here is my ViewPagerAdabter (ViewPagerAdapter.java):
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class ViewPagerAdapter extends PagerAdapter {
private Context mContext;
private int[] mResources;
public ViewPagerAdapter(Context mContext, int[] mResources) {
this.mContext = mContext;
this.mResources = mResources;
}
#Override
public int getCount() {
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.pager_item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.img_pager_item);
imageView.setImageResource(mResources[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
And here the pager_item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:src="#mipmap/abc1"
android:id="#+id/img_pager_item"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:clickable="false"/>
</LinearLayout>
When I run my application and click on my play button instead od going to the swipe view page I see the playbutton.xml.
Does anyone knows where the problem is?
If you want to show dots pager indicator then I am attaching link through which you can implement dots pager indicator easily. I personally recommend it. with this even you can work with infinite pager indicator
Follow this link

How to assign buttons on different spots of 70 images separately?

My Problem:
I have 70 images, and on each image I want to put transparent button
in such a way that when user taps on it, it plays a short audio
regarding the spot on image. Images are displaying in a ViewPager.
My Solution:
Now what I have in mind is I can create 70 fragments each containing respective image as background and I can assign button on each spot easily and assign actions to those buttons which will play their respective audio.
But
this doesn’t look like a good approach to include 70 fragments in a single app.
So how can I achieve this, and what would be a better approach I can use?
We can just have one fragment and create an ArrayList of Map(Button, RelatedAudioFile) data structure for holding buttons and related audio files. ArrayList index represents the page number.
Example:
Now lets say we have 3 viewPages. As most of the PagerAdapter index start from "0", let say Page-0 contains 3 buttons, Page-1 contains 1 button, Page-2 contains 2 buttons.
Pseudocode:
class PagerHolder extends Fragment {
//buttons list - here, arrayList index represents page number
//and at each index we have map of buttons (buttons in each of these pages) and the related audio files
private ArrayList<Map<Button, RelatedAudioFile>> pageButtonsList = new ArrayList<>();
//pager view
private ViewPager viewPager;
//pager adapter
private PagerAdapter pagerAdapter;
//current page number -- page in which we are in right now
private int currentpageNumber = 0;
//buttonListener -- one button listener for all the buttons in all the pages.
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View buttonView) {
//here you can play the audio.
//buttonView -- is the same button-object that was pressed.
((RelatedAudioFile)pageButtonsList.get(currentpageNumber).get(buttonView)).play();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pagerAdapter = new PagerAdapter(getChildFragmentManager());
//add buttons to the list
//page 0 buttons
HashMap<Button, RelatedAudioFile> page0Buttons = new HashMap<>();
page0Buttons.put(new Button(context), new RelatedAudioFile());
page0Buttons.put(new Button(context), new RelatedAudioFile());
page0Buttons.put(new Button(context), new RelatedAudioFile());
pageButtonsList.add(page0Buttons)
//Adding page 1 buttons:
HashMap<Button, RelatedAudioFile> page1Buttons = new HashMap<>();
page1Buttons.put(new Button(context), new RelatedAudioFile());
pageButtonsList.add(page1Buttons);
//Adding page 2 buttons:
HashMap<Button, RelatedAudioFile> page2Buttons = new HashMap<>();
page2Buttons.put(new Button(context), new RelatedAudioFile());
page2Buttons.put(new Button(context), new RelatedAudioFile());
pageButtonsList.add(page2Buttons);
for(Map<Button, RelatedAudioFile> pageButtons :pageButtonsList) {
for(Button button : pageButtons.keySet()) {
button.setOnClickListener(listener);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_editor_pager, container, false);
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
viewPager.setAdapter(pagerAdapter);
return v;
}
private class PagerAdapter extends FragmentPagerAdapter {
private ButtonFragment buttonFragment;
private PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pageNumber) {
currentpageNumber = pageNumber;
//pass the buttons to the fragment so that it can add these buttons to the screen
buttonFragment = ButtonFragment.newInstance(pageButtonsList.get(pageNumber).keySet());
//to add buttons on screen programatically at certain position you can refer here:
// http://stackoverflow.com/questions/3441475/android-change-absolute-position-of-a-view-programmatically
}
//number of pages
#Override
public int getCount() {
return 70;
}
}
You dont have to create 70 fragments. Instead, you could just use one ImageView as follows:
final List<Integer> list = new ArrayList<>();
list.add(R.drawable.img_0);
list.add(R.drawable.img_1);
...
list.add(R.drawable.img_69);
ImageView img = (ImageView)findViewById(R.id.imageView);
img.setBackgroundResource(list.get(yourIndex));
img.setOnClickListener(new OnClickListener());//plays the audio
You don't need to declare 70 fragments, just create one fragment and on that fragment declare global arrays of images and sound. Now when you redirect here at fragment just pass one integer variable in argument. So now you can display the image from array using that integer variable and on button click you can play audio from sound array using same integer number.
Use this custom view pager
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
* Created by Jinesh on 06-01-2016.
*/
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
/*
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
*/
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
Add this tag to your xml
<Your_package_name.CustomViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vP_asq_Pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
Then extend PagerAdapter
public class HomeAdapter extends PagerAdapter {
public HomeAdapter(){
}
#Override
public int getCount() {
return mItemList.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) container.getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.adapter_surveyquestion_view, null);
/*do your operations on your views here
store the 70 images in arraylist and return the size of the arraylist in getCount() method of the adapter.show different images each time in
getView based on the position variable.*/
(container).addView(v);
return v;
}
#Override
public boolean isViewFromObject (View view, Object object){
return view == ((View) object);
}
#Override
public void restoreState (Parcelable arg0, ClassLoader arg1){
}
#Override
public Parcelable saveState () {
return null;
}
#Override
public void destroyItem (ViewGroup container,int position, Object object){
container.removeView((View) object);
}
}
This is how I would do. Pleas note that this is a single class solution for example purpose, you can separate classes
This will keep only 5 fragments at a time
Screen is divided into 4 buttons you can set alpha value of buttons and size as per need currently i kept it half transparent for example
I am using Glide for image loading to avoid OOM problem because of image loading
What it look like
The Solution :-
package com.example.sample;
import java.util.ArrayList;
import com.bumptech.glide.Glide;
import android.content.Context;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
public class MainActivity extends FragmentActivity {
private static ArrayList<Integer> imageList = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Load image data
for (int i = 0; i < 70; i++) {
imageList.add(R.drawable.ic_launcher);
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
ViewPager viewPager = (ViewPager) rootView
.findViewById(R.id.image_pager);
// Limit number of pages that should be retained to either
// side of the current page
viewPager.setOffscreenPageLimit(2);
viewPager.setAdapter(new SongDetailAdapter(getActivity()));
return rootView;
}
}
public static class SongDetailAdapter extends PagerAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
public SongDetailAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((FrameLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = mLayoutInflater.inflate(
R.layout.image_place_holder, container, false);
ImageView imageView = (ImageView) itemView
.findViewById(R.id.background);
itemView.findViewById(R.id.button1).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
playSound(1);
}
});
itemView.findViewById(R.id.button2).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
playSound(2);
}
});
itemView.findViewById(R.id.button3).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
playSound(3);
}
});
itemView.findViewById(R.id.button4).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
playSound(4);
}
});
Glide.with(mContext).load("").placeholder(imageList.get(position))
.crossFade(300).into(imageView);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((FrameLayout) object);
}
#Override
public Object instantiateItem(View arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
/*
* Play sound
*/
private void playSound(int buttonNumber) {
switch (buttonNumber) {
case 1: // play sound for Button1
case 2: // play sound for Button2
case 3: // play sound for Button3
case 4: // play sound for Button4
default: // play sound for Button n
// Playing default notification here for example
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager
.getRingtone(mContext, notification);
r.play();
break;
}
}
}
}
Layouts
Main Activity layout activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sample.MainActivity"
tools:ignore="MergeRootFrame" />
Main fragment layout fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.sample.MainActivity$PlaceholderFragment" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/image_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Image place holder with dummy buttons imae_place_holder.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:alpha=".5"
android:background="#android:color/white"
android:text="Button" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:alpha=".5"
android:background="#android:color/holo_green_light"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:alpha=".5"
android:background="#android:color/holo_blue_light"
android:text="Button" />
<Button
android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:alpha=".5"
android:background="#android:color/holo_red_light"
android:text="Button" />
</LinearLayout>
</LinearLayout>
</FrameLayout>

Categories

Resources