I would like to simulate the animation of a view pager, for changing the background color, but the idea is to have a view (or more) that stays in front of the background at all time (even when switching it).
Any suggestion would be really nice to hear.
Edit: This is an example of what I`m trying to achieve:
http://www.youtube.com/watch?v=mB7GmfMxLvY
There are couple of ways how this can be done. You can create views with different background and then use animations to get the desired effect. However, since you mentioned ViewPager, and if that is what you need.. an easier solution is use a Relative layout and overlay other views on top of a view pager.
Take a look here:
<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:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/viewpager"
android:layout_alignParentRight="false"/>
<!-- other views go here -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="#drawable/ic_launcher"/>
</RelativeLayout>
Then assign views to the view pager with different background colors. (Note: written the code in short time to explain the solution)
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
colors = new ArrayList<Integer>();
colors.add(Color.RED);
colors.add(Color.BLACK);
colors.add(Color.BLUE);
colors.add(Color.GREEN);
colors.add(Color.YELLOW);
mViewPager = (ViewPager)findViewById(R.id.viewpager);
mPageAdapter = new MyPageAdapter();
mViewPager.setAdapter(mPageAdapter);
mPageAdapter.notifyDataSetChanged();
}
private MyPageAdapter mPageAdapter;
private ViewPager mViewPager;
private List<Integer> colors;
class MyPageAdapter extends PagerAdapter {
#Override
public int getCount() {
return colors.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
RelativeLayout view = new RelativeLayout(getApplicationContext());
view.setBackgroundColor(colors.get(position));
((ViewPager) mViewPager).addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object view) {
((ViewPager) mViewPager).removeView((RelativeLayout) view);
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == ((RelativeLayout) o);
}
}
}
So this way you can achieve all the properties of the view pager (gestures, slide effect etc.) without writing any extra code).
Related
I want to implement the following screen :
In the screen shot you can see that below MyAdvisor TextView i have an image.On swiping this image different image will be displayed .To create Swipe Gallery i am using view pager here.I am using an Adapter which is providing images to display through view pager.
Adapter:
public class ImageAdapter extends PagerAdapter {
private Context context;
private int[] images = new int[]{R.drawable.imgone,
R.drawable.img2,
R.drawable.img3};
public ImageAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.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.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(images[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Below is the xml file of demo project of mine which contains two text view and a view pager.
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:layout_above="#+id/txt"
android:layout_marginTop="15sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txt"
android:text="Hello2"
android:layout_above="#+id/pager"
android:layout_marginTop="15sp"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height = "wrap_content"
></android.support.v4.view.ViewPager>
My problem is that the view pager is having height as match_parent.Even after changing it as wrap_content ,the other views are not displayed .Please guide me how can i implement this screen.
I suggest you to use Heterogenous Layouts inside RecyclerView for that approach.If you're not familiar with the concept, go thru this tutorial.And for the viewpager part, there is this awesome library which comes up with so many built in features that you will absolutely love.Just inflate the Sliderlayout of this library inside onCreateViewHolder() of adapter and provide corresponding data.No need to write your own custom pageradapter and handle events.You just have to know how to use Recyclerview and you're pretty much done.
I'm using ViewPager. I want to put a button on each page, but in doing so fills the entire page. I would like to determine the width and height of button but do not know how.
This is my code:
Pager Activity
public class PagerActivity extends Activity {
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
//Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
//A little space between pages
pager.setPageMargin(15);
//If hardware acceleration is enabled, you should also remove
// clipping on the pager for its children.
pager.setClipChildren(false);
}
//Nothing special about this adapter, just throwing up colored views for demo
private class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView view = new TextView(PagerActivity.this);
view.setText("Item "+position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50, position * 10, position * 50));
view.setTextColor(Color.parseColor("#CA2C68"));
Button buttonView = new Button(PagerActivity.this);
buttonView.setBackgroundResource(R.drawable.button_states_azul);
container.addView(buttonView);
return buttonView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#FF7CB8"
android:id="#+id/linear" >
<View
android:layout_width="match_parent"
android:layout_height="4dp"
android:background="#CA2C68"
android:layout_gravity="bottom"/>
</LinearLayout>
<com.example.slidee.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/linear"
android:layout_alignParentBottom="true"
android:layout_below="#+id/linear"
android:background="#29C5FF" >
<android.support.v4.view.ViewPager
android:layout_width="234dp"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:background="#29C5FF" />
</com.example.slidee.PagerContainer>
ViewPager expects the contained view to occupy the whole container.
Use some layout to contain a button:
LinearLayout lay = new LinearLayout(PagerActivity.this);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
buttonView.setLayoutParams(lp);
lay.addView(buttonView);
container.addView(lay);
an other way to do it is to make a new xml file and inflate it.
<?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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/viewpager_button"
android:background="#drawable/button_states_azul"/>
</LinearLayout>
and in instantiateItem
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
View pagerView = inflater.inflate(R.layout.viewpager_layout, null);
Button button = (Button) pagerView.findViewById(R.id.viewpager_button);
container.addView(button);
You are creating the button dynamically and hence by default it does a match_parent for width and height.
Add this line:
buttonView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
This is how i do it, create a xml layout you want to inflate. Add all the view you are intending. Then inside your adapter class, inside instantiateItem override do something like this. remember to adjust your xml views to fit parents width and height as you wish.
#Override
public Object instantiateItem(ViewGroup container, final int position) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.your_view, container, false);
// get reference to your button over here if you have one
Button b = (Button) view.findViewById(R.id.enter_button);
container.addView(view);
return view;
}
UPDATED : Can I use the following layout to implement 3 textviews in Viewpager :
<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">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="view 1"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="view 2"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="view 3"/>
</android.support.v4.view.ViewPager>
</LinearLayout>
I want to implement the ViewPager for these 3 views. and i want to have viewpager and those 3 views in single xml file. Each page contains each textview. I have seen some examples but each page was implement using separate xml layout file.
How can I implement the viewpager for these 3 views in a single xml file. If possible please provide me a sample code or example.
You can use a single XML layout nesting the children views.
<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="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/page_one"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:text="PAGE ONE IN"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#fff"
android:textSize="24dp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/page_two"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:text="PAGE TWO IN"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#fff"
android:textSize="24dp"/>
</LinearLayout>
</android.support.v4.view.ViewPager>
</LinearLayout>
BUT... you need handle this with an adapter also. Here we return the finded view ID without inflate any other layout.
class WizardPagerAdapter extends PagerAdapter {
public Object instantiateItem(View collection, int position) {
int resId = 0;
switch (position) {
case 0:
resId = R.id.page_one;
break;
case 1:
resId = R.id.page_two;
break;
}
return findViewById(resId);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
}
// Set the ViewPager adapter
WizardPagerAdapter adapter = new WizardPagerAdapter();
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
My question is... Some Guru here can teach me if is possible that the ViewPager read the children from XML and auto build the pages without use the instantiateItem()?
Update
This answer will show optimised and managed way to set ViewPager pages inside layout.
Step 1
First make two pages Layouts XML layout_page_1.xml and layout_page_2.xml.
Step 2
Now include all pages layout in your parent layout ViewPager.
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/page_one"
layout="#layout/layout_page_1" />
<include
android:id="#+id/page_two"
layout="#layout/layout_page_2" />
</androidx.viewpager.widget.ViewPager>
Step 3
Now from your code, set adapter in simple steps
// find views by id
ViewPager viewPager = findViewById(R.id.viewpager);
CommonPagerAdapter adapter = new CommonPagerAdapter();
// insert page ids
adapter.insertViewId(R.id.page_one);
adapter.insertViewId(R.id.page_two);
// attach adapter to viewpager
viewPager.setAdapter(adapter);
That's All! You need only a common adapter for all ViewPagers.
CommonPagerAdapter.java class
public class CommonPagerAdapter extends PagerAdapter {
private List<Integer> pageIds = new ArrayList<>();
public void insertViewId(#IdRes int pageId) {
pageIds.add(pageId);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
return container.findViewById(pageIds.get(position));
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return pageIds.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
}
Important Note
It is better to use Fragments instead of Views. You should create Fragments and use FragmentStatePagerAdapter to maintain stack, lifecycle and states. You can see #this answer for complete code of using FragmentStatePagerAdapter.
thats impossible .you can do it like these
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
then create seperate xml file and do it like this.for eg:i am gonna use the xml file name is ios_frag.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:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50sp"/>
</LinearLayout>
Just if anyone faces the same problem, I've solved it with an adapter which extracts the page views from an arbitrary viewgroup that you pass to it.
package com.packagename;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class ViewGroupPagerAdapter extends PagerAdapter {
public ViewGroupPagerAdapter(ViewGroup viewGroup) {
while (viewGroup.getChildCount() > 0) {
views.add(viewGroup.getChildAt(0));
viewGroup.removeViewAt(0);
}
}
private List<View> views = new ArrayList<View>();
#Override
public Object instantiateItem(ViewGroup parent, int position) {
View view = views.get(position);
ViewPager.LayoutParams lp = new ViewPager.LayoutParams();
lp.width = ViewPager.LayoutParams.FILL_PARENT;
lp.height = ViewPager.LayoutParams.FILL_PARENT;
view.setLayoutParams(lp);
parent.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup parent, int position, Object object) {
View view = (View) object;
parent.removeView(view);
}
#Override
public int getCount() {
return views.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Usage:
ViewPager viewPager=findViewById(...); // Retrieve the view pager
viewPager.setAdapter(new ViewGroupPagerAdapter(findViewById(R.id.id_of_your_view_group_where_you_store_the_pages)));
You can subclass ViewPager and override onInflate.
Moreover, you will get a preview of the first ViewPager page in the Layout Editor.
All views are kept in memory so for performance reasons you should only use this with a small number of pages.
#Override protected void onFinishInflate() {
int childCount = getChildCount();
final List<View> pages = new ArrayList<>(childCount);
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
Class<?> clazz = child.getClass();
if (clazz.getAnnotation(DecorView.class) == null) {
pages.add(child);
}
}
for (View page : pages) {
removeView(page);
}
setAdapter(new PagerAdapter() {
#Override public int getCount() {
return pages.size();
}
#Override public Object instantiateItem(ViewGroup container, int position) {
container.addView(pages.get(position));
return position;
}
#Override public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(pages.get((Integer)object));
}
#Override public boolean isViewFromObject(View view, Object object) {
return pages.get((Integer)object) == view;
}
});
super.onFinishInflate();
}
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(rootView));
viewPager.setOffscreenPageLimit(3); //or whatever you like
it caches it and shows perfectly.
How can I implement the viewpager for these 3 views in a single xml file.
Sorry, but that is not possible.
add this in your xml layout file
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
create 3 Fragments and add each TextView for every fragment. Then create an adapter that subclassed PagerAdapter
A good example can be found here
Simply : add a ViewPager in your file and put inside your 3 TextView...
After trying out the Gallery and Horizontal Scroll View, I found that the View Pager does what I need but with one minor thing missing. Can the View Pager have multiple views per page?
I know that View Pager shows only 1 view/page per swipe. I was wondering if I can limit my views width so my 2nd view following it will show?
For example: I have 3 views and I want the screen to show view 1 and part of view 2 so the user knows there is more content so they can swipe to view 2.
|view 1|view 2|view 3|
|screen |
I discovered that a perhaps even simpler solution through specifying a negative margin for the ViewPager. I've created the MultiViewPager project on GitHub, which you may want to take a look at:
https://github.com/Pixplicity/MultiViewPager
Although MultiViewPager expects a child view for specifying the dimension, the principle revolves around setting the page margin:
ViewPager.setPageMargin(
getResources().getDimensionPixelOffset(R.dimen.viewpager_margin));
I then specified this dimension in my dimens.xml:
<dimen name="viewpager_margin">-64dp</dimen>
To compensate for overlapping pages, each page's content view has the opposite margin:
android:layout_marginLeft="#dimen/viewpager_margin_fix"
android:layout_marginRight="#dimen/viewpager_margin_fix"
Again in dimens.xml:
<dimen name="viewpager_margin_fix">32dp</dimen>
(Note that the viewpager_margin_fix dimension is half that of the absolute viewpager_margin dimension.)
We implemented this in the Dutch newspaper app De Telegraaf Krant:
Mark Murphy has an interesting blog post addressing precisely this problem. Although I ended up using my own solution in this thread, it's worthwhile looking at Dave Smith's code, which Mark references in the blog post:
https://gist.github.com/8cbe094bb7a783e37ad1/
Warning! Before you take this approach, beware of some very serious issues with this approach, mentioned both at the end of this post and in the comments below.
You'll end up with this:
It effectively works by wrapping a ViewPager into a subclass of FrameLayout, setting it to a specific size, and calling setClipChildren(false). This inhibits Android from clipping the views that exceed beyond the boundaries of the ViewPager, and visually accomplishes what you want.
In XML, it's very simple:
<com.example.pagercontainer.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCC">
<android.support.v4.view.ViewPager
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
</com.example.pagercontainer.PagerContainer>
Add in a little code for handling touch events from outside of the ViewPager and invalidating the display when scrolling, and you're done.
That being said, and while this works great in general, I did notice that there is an edge-case that isn't solved with this fairly simple construction: when calling setCurrentPage() on the ViewPager. The only way I could find to resolve this was by subclassing ViewPager itself and having its invalidate() function also invalidate the PagerContainer.
It is possible to show more than one page on the same screen.
One of the ways is by overriding the getPageWidth() method in the PAgerAdapter. getPageWidth() returns a float number between 0 and 1 indicating how much width of the Viewpager should the page occupy. By default it is set to 1. So, you can change this to the width you wish.
You can read more about this here & github project.
This is how I got it:
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center"
android:layout_marginBottom="8dp"
android:clipToPadding="false"
android:gravity="center"
android:paddingLeft="36dp"
android:paddingRight="36dp"/>
and in activity,i use this :
markPager.setPageMargin(64);
hope it helps!
I had the same problem with the only difference that i needed to show 3 pages at once (previous, current and next pages). After a really long research for the best solution i think i found it.
The solution is a mix of few of the answers here:
As #Paul Lammertsma's answer pointed out - Dave Smith's code in Mark Murphy's blog is the basis for the solution. The only problem for me was that the ViewPager was only on the top part of the screen due to the size they give it in the xml file:
android:layout_width="150dp"
android:layout_height="100dp"
Which wasn't good for my purpose since i was looking for something that will spread all over the screen. So i changed it to wrap the content as you can see here:
<com.example.nutrino_assignment.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCC">
<android.support.v4.view.ViewPager
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</com.example.nutrino_assignment.PagerContainer>
Now I lost all the effect of what the tutorial was trying to do. Using #andro's answer i was able to show more then 1 page at a time: exactly 2! The current and the next.
Did so by overriding as follow:
#Override
public float getPageWidth(int position) {
return(0.9f);
}
That was almost what i needed... (even though i think its enough for what you were asking), but for others who might need something like what i was needed:
For the last part of the solution i used the idea in this answer, again by #Paul Lammertsma.
In Dave Smith's code you will find in the onCreate method this line:
//A little space between pages
pager.setPageMargin(15);
which i replaced with:
//A little space between pages
pager.setPageMargin(-64);
now on the first page looks:
|view 1|view 2|view 3|
|screen |
while on the 2nd it looks like:
|view 1|view 2|view 3|
|screen |
Hope it will help someone! I wasted like 2 days on it...
Good luck.
viewPager.setPageMargin(-18);// adjust accordingly ,-means less gap
in imageadapter
private class ImagePagerAdapter2 extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.add1,
R.drawable.add3,
R.drawable.add4,
R.drawable.add2,
};
#Override
public float getPageWidth(int position) {
return .3f;
}
adjust return value...lesser means more image......0.3 means atleast 3 images at a time.
LayoutParams lp = new LayoutParams(width,height);
viewpager.setLayoutParams(lp);
In xml file using this code(Main Activity)
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="130dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="vertical"
android:weightSum="1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="130dp">
<com.wonderla.wonderla.muthootpathanamthitta.activity_muthootpathanm.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="100dip"
android:layout_height="100dip"/>
</com.wonderla.wonderla.muthootpathanamthitta.activity_muthootpathanm.PagerContainer>
</RelativeLayout>
</LinearLayout>
Main activity xml file add this code
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="130dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="vertical"
android:weightSum="1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="130dp">
<com.wonderla.wonderla.muthootpathanamthitta.activity_muthootpathanm.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="100dip"
android:layout_height="100dip"/>
</com.wonderla.wonderla.muthootpathanamthitta.activity_muthootpathanm.PagerContainer>
</RelativeLayout>
</LinearLayout>
Main Activity code
public class MainActivity extends Activity{
final Integer[] XMEN2= {R.mipmap.bookticket,R.mipmap.safty,R.mipmap.privacy};
private ArrayList<Integer> XMENArray2 = new ArrayList<Integer>();
PagerContainer mContainer;
int currentPage2 = 0;
private static int NUM_PAGES2 = 0;
ViewPager mPager2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
initData2();}
private void initViews() {
mPager2 = (ViewPager)findViewById(R.id.viewpager);
mContainer = (PagerContainer)findViewById(R.id.pager_container);
mPager2.setOffscreenPageLimit(5);
mPager2.setPageMargin(15);
mPager2.setClipChildren(false);
}
private void initData2() {
for(int i=0;i<XMEN2.length;i++)
XMENArray2.add(XMEN2[i]);
mPager2.setAdapter(new Sliding_Adaptertwo(getActivity(),XMENArray2));
NUM_PAGES2 =XMEN2.length;
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage2 == NUM_PAGES2) {
currentPage2= 0;
}mPager2.setCurrentItem(currentPage2++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
}
}
Pager View pagercontainer class
import android.content.Context;
import android.graphics.Point;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
public class PagerContainer extends FrameLayout implements ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
//Disable clipping of children so non-selected pages are visible
setClipChildren(false);
//Child clipping doesn't work with hardware acceleration in Android 3.x/4.x
//You need to set this value here if using hardware acceleration in an
// application targeted at these releases.
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y - mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
#Override
public void onPageSelected(int position) { }
#Override
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
and its Adapter
public class Sliding_Adaptertwo extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public Sliding_Adaptertwo(Context context, ArrayList<Integer> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.sliding_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
xml file of adapter class
<?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="fill_parent"
>
<ImageView
android:id="#+id/image"
android:layout_width="90dp"
android:layout_height="90dp"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/ad1"
/>
</FrameLayout>
it works fine
I want to create some scroll view using Horizontal View Pager. Left view must has full screen width, but right only a quarter of width (it will be a vertical panel like in Dolphin browser). It's possible to do that? I changed android:layout_width in right layout, but it didn't work.
My code:
public class TestActivity extends FragmentActivity {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager pager = (ViewPager) findViewById(R.id.panelPager);
pager.setAdapter(adapter);
pager.setCurrentItem(0);
}
}
main_view.xml
<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/panelPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MyPagerAdapter.java
public class MyPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 2;
}
#Override
public Object instantiateItem(final View collection, final int position) {
LayoutInflater inflater =
(LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.left;
break;
case 1:
resId = R.layout.right;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(final View arg0, final int arg1, final Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(final View arg0, final Object arg1) {
return arg0 == ((View) arg1);
}
left.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LEFT" />
</LinearLayout>
right.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="50dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/light_blue" >
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="RIGHT"/>
</LinearLayout>
Check Murphy's answer on this question. You need to override PagerAdapter's getPageWidth() method on your PagerAdapter class, like this for example:
#Override
public float getPageWidth(int page) {
if(page==0) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return (float)LEFT_FRAGMENT_PIXEL_WIDTH / size.x;
}
else
return super.getPageWidth(page);
}
Looking at the source for ViewPager, this isn't something it's designed to do; it uses its own width to calculate scroll distances etc, with the clear assumption that all children will have the same width as the ViewPager itself.
For your specific case there may be a hacky workaround, though. You can specify a margin between adjacent pages, and this margin can be negative. This may give the result you want, provided the Z-ordering of the ViewPager's children is appropriate. Give it a try, and see whether it does what you need.
Adrian is exactly right. ViewPager isn't designed to show a portion of the next post as a preview/teaser but it can do it. In my ViewPagerCursorAdapter extends PagerAdapter class I run this:
public Object instantiateItem(View collection, final int position) {
cursor.moveToPosition(position);
View newView = getPageView(cursor, collection);
if (cursor.getCount() > 1) {
((ViewPager)collection).setPageMargin(-overlapMargin);
if (! cursor.isLast()) { newView.setPadding(0, 0, overlapMargin, 0); }
}
((ViewPager) collection).addView(newView);
return newView; //returns the object reference as the tag for identification.
}
You will run into a strange z overlapping issue. The trick is to either apply the background only to ViewPager's background or to apply it to the view inside the newView you just set the padding for. Looks good and works great.