One of my layouts inside of my ViewPager has a button. "R.layout.add_site". I would like the option of hitting the button and it scroll to the specific page for me. I already have the option to swipe to the specific page, but I would like to have both.
Now I'm sure there's a way to do that, but for some reason, I cannot figure it out.
You'll see that I've made an attempt , but just dont know what method to call in order to make it scroll to the desired page. Which is R.layout.main.
Here's my code.
public class fieldsActivity extends Activity {
Button addSiteButton;
Button cancelButton;
Button signInButton;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to create a custom title bar for activity window
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
// use custom layout title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
Pager adapter = new Pager();
ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
mPager.setAdapter(adapter);
mPager.setCurrentItem(1);
addSiteButton = (Button) findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Don't know what method to call!?
}
});
cancelButton = (Button) findViewById(R.id.cancel_button);
signInButton = (Button) findViewById(R.id.sign_in_button);
}
private class Pager extends PagerAdapter {
public int getCount() {
return 3;
}
#Override
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.field01;
break;
case 1:
resId = R.layout.add_site;
break;
case 2:
resId = R.layout.main;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#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() {
return null;
}
}
}
Any help is appreciated!
call :
mPager.setCurrentItem(2);
in your onClick() method, or for a smoother scroll:
mPager.setCurrentItem(2, true);
I can't really answer WHY exactly this happens, but if you delay the setCurrentItem call for a few milliseconds it should work. My guess is that because during onResume there hasn't been a rendering pass yet, and the ViewPager needs one or something like that.
private ViewPager viewPager;
#Override
public void onResume() {
final int pos = 3;
viewPager.postDelayed(new Runnable() {
#Override
public void run() {
viewPager.setCurrentItem(pos);
}
}, 100);
}
Original Answer: here
Related
I'm a little desperate with viewpagers / different layouts shown in them.
Summarized: Switching through different layouts works perfectly. Now I want to implement buttons / functionality on the different layouts, which doesn't work.
I have the following viewpager which functions well. It iterates through the layouts-list and shows the different layouts.
My Activity
public static final String LOG_TAG = MainActivity.class.getSimpleName();
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_swipe);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
//btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
layouts = new int[] {
R.layout.activity_mmg_description_start,
R.layout.activity_mmg_question_1,
R.layout.activity_mmg_question_2,
R.layout.activity_mmg_question_3,
R.layout.activity_mmg_question_4,
R.layout.activity_mmg_question_5,
R.layout.activity_mmg_question_6,
R.layout.activity_mmg_question_7,
R.layout.activity_mmg_question_8,
R.layout.activity_mmg_question_9,
R.layout.activity_mmg_question_10,
R.layout.activity_mmg_question_11,
R.layout.activity_mmg_question_12,
R.layout.activity_mmg_question_13,
R.layout.activity_mmg_question_14
};
// adding bottom dots
addBottomDots(0);
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
#
Override
public void onBackPressed() {}
public void btnNextClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#
Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start_measurement_manual));
//btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
//btnSkip.setVisibility(View.VISIBLE);
}
}
#
Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#
Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(getResources().getColor(R.color.dot_inactive));
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(getResources().getColor(R.color.dot_active));
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
startActivity(new Intent(this, ManualActivity.class));
finish();
}
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#
Override
public Object instantiateItem(ViewGroup container, int position) {
//Inflate the correct layout
layoutInflater = (LayoutInflater) getSystemServ**Option 1: starting with layout activity_mmg_question_1**ice(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], container, false);
((ViewPager) container).addView(inflatedView, 0);
switch (position) {
case R.layout.activity_mmg_description_start:
Log.d(LOG_TAG, "QD " + "Firstviewcame");
case R.layout.activity_mmg_question_1:
//LinearLayout linearLayout_mmg_1 = (LinearLayout)inflatedView.findViewById(R.id.linearlayout_mmg_1);
Button testButton = (Button) findViewById(R.id.testbutton);
testButton.setOnClickListener(new View.OnClickListener() {
#
Override
public void onClick(View v) {
Log.d(LOG_TAG, "QD " + "Swipebuttonclicked");
}
});
}
return inflatedView;
}
#
Override
public int getCount() {
return layouts.length;
}
#
Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#
Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I want to add functionality to the different layouts. On layout: activity_mmg_question_1 is a button (R.id.testbutton) which should write a log message.
I've tried a few options.
Option 1: starting with layout activity_mmg_question_1
Outcommenting the R.layout.activity_mmg_description_start at the beginning:
layouts = new int[]{
//R.layout.activity_mmg_description_start,
R.layout.activity_mmg_question_1,
The following code works:
#Override
public Object instantiateItem(ViewGroup container, int position) {
//Inflate the correct layout
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], container, false);
((ViewPager)container).addView(inflatedView,0);
LinearLayout linearLayout_mmg_1 = (LinearLayout)inflatedView.findViewById(R.id.linearlayout_mmg_1);
Button testButton = (Button)findViewById(R.id.testbutton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d (LOG_TAG, "QD " + "Swipebuttonclicked");
}
});
return inflatedView;
}
Quite understandable: It inflates the layout, finds the button, works.
Option 2: starting with layout activity_mmg_description_start
Starting with R.layout.activity_mmg_description_start at the beginning:
layouts = new int[]{
R.layout.activity_mmg_description_start,
R.layout.activity_mmg_question_1,
It ends up with a
FATAL EXCEPTION: main
[...]
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I think I also got this: on the first layout (R.layout.activity_mmg_description_start) it doesn't find the button, so it points to null, and the error shows up.
How to prevent this? That led me to the idea of:
Option 3: switch-case
Displaying of the different layouts works, but the log-message from the button doesn't work.
#Override
public Object instantiateItem(ViewGroup container, int position) {
//Inflate the correct layout
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], container, false);
((ViewPager)container).addView(inflatedView,0);
switch (position){
case R.layout.activity_mmg_description_start:
Log.d (LOG_TAG, "QD " + "Firstviewcame");
case R.layout.activity_mmg_question_1:
//LinearLayout linearLayout_mmg_1 = (LinearLayout)inflatedView.findViewById(R.id.linearlayout_mmg_1);
Button testButton = (Button)findViewById(R.id.testbutton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d (LOG_TAG, "QD " + "Swipebuttonclicked");
}
});
}
return inflatedView;
}
Does anybody have an idea or solution?
Best and thanks in advance,
tigercode
I think you should use Fragments.
Try to setOnClickListener before call ((ViewPager)container).addView(inflatedView,0);
public Object instantiateItem(ViewGroup container, int position) {
//Inflate the correct layout
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], container, false);
switch (position){
case R.layout.activity_mmg_description_start:
Log.d (LOG_TAG, "QD " + "Firstviewcame");
case R.layout.activity_mmg_question_1:
//LinearLayout linearLayout_mmg_1 = (LinearLayout)inflatedView.findViewById(R.id.linearlayout_mmg_1);
Button testButton = (Button)findViewById(R.id.testbutton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d (LOG_TAG, "QD " + "Swipebuttonclicked");
}
});
}
((ViewPager)container).addView(inflatedView,0);
return inflatedView;
}
The following code scrolls the 4 pages just fine. My problem is that the onPageScrolled event does not get triggered when the pages are scrolled. This occurs whether or not I use the myPager.SetOffsccreenPageLimit(4) command. After reading the docs, it is my understanding that when I have implements ViewPager.OnPageChangeListener included in the MyPagerAdapter class that the event should be triggered. What am I doing wrong?
Thanks,
Gary Blakely
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.mysevenpanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
myPager.setOffscreenPageLimit(4);
}
private class MyPagerAdapter extends PagerAdapter
implements ViewPager.OnPageChangeListener {
public int getCount() {
return 4;
}
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.left;
break;
case 1:
resId = R.layout.gps;
break;
case 2:
resId = R.layout.map;
break;
case 3:
resId = R.layout.right;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
int myint = 9;
myint = myint * 2;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int myint = 9;
myint = myint * 2;
}
#Override
public void onPageSelected(int arg0) {
int myint = 9;
myint = myint * 2;
}
}
You also need to set the listener using setOnPageChangeListener().
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.mysevenpanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
myPager.setOffscreenPageLimit(4);
myPager.setOnPageChangeListener(adapter); // This line here
}
I believe that you also need to register your Adapter instance as a listener for those types of events too using .setOnPageChangeListener() on the ViewPager.
You need to set a listener, but setOnPageChangeListener(OnPageChangeListener) is deprecated. You should use addOnPageChangeListener(OnPageChangeListener) to be able to have multiple listeners instead.
I'm fairly new to Android development so I ran into a problem with the onResume() method.
My code crashes when I try to write Name.setText() from within the onResume() method.
Writing the TextView from within the onPause() method works surprisingly without any problem.
How can I access this TextView from within the onResume() method?
public class Main extends Activity {
private ViewPager awesomePager;
private static int NUM_AWESOME_VIEWS = 2;
private Context cxt;
private AwesomePagerAdapter awesomeAdapter;
View v;
TextView Name;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cxt = this;
awesomeAdapter = new AwesomePagerAdapter();
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
}
#Override
protected void onResume() {
super.onResume();
Name.setText("1");
}
#Override
protected void onPause() {
super.onPause();
}
private class AwesomePagerAdapter extends PagerAdapter{
#Override
public int getCount() {
return NUM_AWESOME_VIEWS;
}
#Override
public Object instantiateItem(View collection, int position) {
View v = new View(cxt.getApplicationContext());
final LayoutInflater inflater = (LayoutInflater) cxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (position) {
case 0:
v = inflater.inflate(R.layout.subpage1, null, false);
Name = (TextView) v.findViewById(R.id.name);
break;
case 1:
v = inflater.inflate(R.layout.subpage2, null, false);
break;
default:
break;
}
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView(v);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void finishUpdate(View arg0) {}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View arg0) {}
}
}
Name must be set to null...Your app must have paused before it ever got initialized. Just check to make sure it's initialized before trying to do anything with it. You're onResume() should look like this then:
#Override
protected void onResume() {
super.onResume();
if(Name != null){
Name.setText("1");
}
}
P.S. Standard java convention is to have all variable names begin with a lower case letter. You should probably rename Name to name.
First of all, in your code you don't acquire a reference to the Name text view, so you must be getting NullPointerException.
If you fix that, it should work IMO. If it does not, tell us the exception name you get.
I am using the following code, MAX is 2 pages. By default the position is 0 and adds a new page to the right. I inflate two layout files.
How can I show the page1 when the app starts and add a new page to the left ?
Thanks.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="#+id/pagerView" />
</LinearLayout>
Java code
public class MyPagerActivity extends Activity {
private Context context;
private int pageNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
ViewPager pagerView = (ViewPager)findViewById(R.id.pagerView);
pagerView.setAdapter(new AwesomePagerAdapter());
}
private class AwesomePagerAdapter extends PagerAdapter{
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View)view);
}
#Override
public void finishUpdate(View arg0) {
//setPageTitles(getPageNumber());
}
#Override
public int getCount() {
return 2;
}
#Override
public Object instantiateItem(View collection, int position) {
/* TextView tv = new TextView(MyPagerActivity.this);
tv.setText("Bonjour PAUG " + position);
tv.setTextColor(Color.WHITE);
tv.setTextSize(30);
((ViewPager) collection).addView(tv,0);
return tv;*/
View view = getViewToShow(position);
((ViewPager) collection).addView(view,0);
return view;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==((View)object);
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
#Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
#Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
}
private View getViewToShow(int position){
View view = null;
View layout;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch(position){
case 0:
layout = mInflater.inflate(R.layout.elements, null);
view = layout;
break;
case 1: view =
layout = mInflater.inflate(R.layout.elements2, null);
view = layout;
break;
}
return view;
}
}
Have you tried using the setCurrentItem method?
The accepted solution is fine, but it's important to call this method after setting up the adapter.
viewPager.setAdapter(adapterViewPager);
viewPager.setCurrentItem(1);
By default, you have to set the current value 1 to show the just one default view. If you do not set setCurrentItem to 1, you can not see anything.
viewPager.setAdapter(adapterViewPager);
viewPager.setCurrentItem(1)
This solution gives the ability of setting default page without interference from outside of the Pager adapter class.
#Override
public Object instantiateItem(ViewGroup container, int position) {
View currentPage = null;
switch(position){
case 0:
currentPage = LayoutInflater.from(context).inflate(R.layout.page0, null)
break;
case 1:
currentPage = LayoutInflater.from(context).inflate(R.layout.page1, null)
///////////// This page will be default ////////////////////
((ViewPager)container).setCurrentItem(position);
////////////////////////////////////////////////////////////
break;
case 2:
currentPage = LayoutInflater.from(context).inflate(R.layout.page2, null)
break;
return currentPage;
}
You need to set page only during first initialisation of the fragment. Later it will restore a selected by user position from a "saved instance state". So this looks a little better:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pager.adapter = AwesomePagerAdapter()
if (savedInstanceState == null) {
pager.currentItem = 1
}
}
I'm new to this android and java.
My viewpager now can slide all my xml layout, but i don't know how to access item in them.
I tried using Button mybutton = (Button) findViewById (R.layout.result), then set the onClickListener in mybutton, but then it was forced to close every time I run it.
Here is my code:
public class main extends Activity {
private ViewPager myviewpager;
private ViewPagerAdapter myviewpageradapter;
private static int NUM_AWESOME_VIEWS = 12;
Button button_1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myviewpageradapter = new ViewPagerAdapter();
myviewpager = (ViewPager) findViewById(R.id.myviewpager);
myviewpager.setAdapter(myviewpageradapter);
button_1 = (Button) myviewpager.findViewById(R.id.first_button);
button_1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
private class ViewPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return NUM_AWESOME_VIEWS;
}
#Override
public Object instantiateItem(View collection, int position) {
LayoutInflater layoutinflater = getLayoutInflater();
View view;
view = layoutinflater.inflate(R.layout.page1, null);
switch (position)
{
case 0 : view = layoutinflater.inflate(R.layout.page1, null); break;
case 1 : view = layoutinflater.inflate(R.layout.page2, null); break;
case 2 : view = layoutinflater.inflate(R.layout.page3, null); break;
case 3 : view = layoutinflater.inflate(R.layout.page4, null); break;
case 4 : view = layoutinflater.inflate(R.layout.page5, null); break;
case 5 : view = layoutinflater.inflate(R.layout.page6, null); break;
case 6 : view = layoutinflater.inflate(R.layout.page7, null); break;
case 7 : view = layoutinflater.inflate(R.layout.page8, null); break;
case 8 : view = layoutinflater.inflate(R.layout.page9, null); break;
case 9 : view = layoutinflater.inflate(R.layout.page10, null); break;
case 10 : view = layoutinflater.inflate(R.layout.page11, null); break;
case 11 : view = layoutinflater.inflate(R.layout.result, null);break;
}
((ViewPager) collection).addView(view,0);
return view;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==((View)object);
}
#Override
public void finishUpdate(View arg0) {}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View arg0) {}
}
It may just be the Problem, that your items are not found probably so try this(If your view is no LinearLayout change it)
LayoutInflater getView = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout view1 =(LineaLayout)getView.inflate(R.layout.your_view,null);
But Your Button may throw Exception furthermore there is an onClickListener set to it.
If it's just the Button define it in XML:
android:onClick"buttonClick"
then in Code
public void buttonClick(View v){
// do something
}
If this is not possible because you need to reference the Button later, I stuck with the same Problem and would like to know how it works.
I think the problem here is that you are trying to find a view (findViewById) that wasn't instatiated (inflated) yet. Try to set the button listener inside the instatiateItem method of ViewPagerAdapter type.
Example:
switch(position){
case 0 :
view = layoutinflater.inflate(R.layout.page1, null);
button_1 = (Button) view.findViewById(R.id.first_button);
button_1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
break;
(...)
}