ViewPager access inflated view items - android

I'm trying to implement ViewPager to combine two view within one activity, in which I'm facing NullPointerException when I'm trying to access items using findViewById in inflated views, my custom page adapter is as follows,
public class CustomPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
#Override
public void destroyItem(View view, int value, Object object) {
((ViewPager) view).removeView((View) object);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public Object instantiateItem(View collection, int position) {
LayoutInflater layoutInflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resultId = 0;
switch (position) {
case 1:
resultId = R.layout.layout2;
break;
case 0:
default:
resultId = R.layout.layout1;
break;
}
View view = layoutInflater.inflate(resultId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
}
And my activity is as follows, in which I'm trying to access button which is inside layout1 which throws null value.
public class PageSwiperActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpagerlayout);
Button myButton=(Button) findViewById(R.id.myButton);
}
}
My viewpagerlayout.xml contains only,
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
and my layout1.xml contains one button. Give me some guidance.
Thanks.

Did you set your PageAdapter to ViewPager?
If you don't set it, then remove line with button and add this code to your activity:
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPagerLayout);
viewPager.setAdapter(new CustomPagerAdapter());
instead of this
Button myButton = (Button) findViewById(R.id.myButton);
You can call findViewById to get your button in this method of your adapter:
#Override
public Object instantiateItem(View collection, int position) {
... // your previous code
final Button myButton = (Button) findViewById(R.id.myButton);
return view;
}
after you have inflated layout which contains this button.

After setContentView(R.layout.viewpagerlayout);
you are using
Button myButton=(Button) findViewById(R.id.myButton); directly.
But actually viewpagerlayout doesn't have any view with id myButton.
So that you are getting NULL Pointer Exception. Before using findViewById, you have to add views to ViewPager layout.
In the code you posted here, it seem to be you are adding, but you have to use it after setContentView.

Related

Cannot update views on left and right side of view pager

I have used viewpager which displays view with an image and radiobutton below. Each swipe screen is not a fragment, they are layouts which just swipe the same view with different imageview. The problem is that, I am unable to deselect the radio button which is in left and right side of the current view after i select the radio button of the current screen. If I return POSITION_NONE in getItemPosition(), it refresh the screen and radio button also deselected but the view is flickered. If i am able to call instantiateItem(), my problem is solved . But this method is called only when view is destroyed based on the setOffsetScreenPageLimit(). How can I achieved such requirements, if view pager cannot help?
Fragment:
public class AnswerImageDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener {
//member declaration
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strQuestion = null;
View rootView = inflater.inflate(R.layout.activity_viewpager_demo, container,
false);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
intro_images = (ViewPager) rootView.findViewById(R.id.pager_introduction);
pager_indicator = (LinearLayout) rootView.findViewById(R.id.viewPagerCountDots);
//do some stuff
//set the adapter
mAdapter = new ViewPagerAdapter(getContext(), map);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(clickPosition);
intro_images.setOnPageChangeListener(this);
setUiPageViewController();
bus = EventBus.getDefault();
bus.register(this);
return rootView;
}
//other method
}
PagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// member declaration
public ViewPagerAdapter(Context mContext, HashMap<String, Object> map) {
//other initialization
}
#Override
public int getCount() {
return optionImages.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.pager_item, container, false);
final ImageView ivOption = (ImageView) itemView.findViewById(R.id.answerId); // this is used as radio button in this case
/*The code snippet is to select the answer option based on whether answer is choosen or not.
If choosen, select as default in the pop up answer.
*/
if (null != ans) {
Iterator iterator = ans.iterator();
if (ans.size() > 0) {
int value = (int) iterator.next();
if (value == position) {
ivOption.setImageResource(R.drawable.ic_radio_button_tick);
} else {
ivOption.setImageResource(R.drawable.ic_radio_button_nontick);
}
}
}
p = position;
/*The code snippet is to change the answer value based on the user selection.
This means if user choosen another answer then clear the earlier choosen answer
*/
ivOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
txtQuestion.setText(question);
txtOption.setText(optionsList.get(position));
imageView.setParseFile(optionImages.get(position));
imageView.loadInBackground();
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
LinearLayout ll = (LinearLayout) object;
/*RelativeLayout ivOption = (RelativeLayout) ll.getChildAt(2);
ImageView iv = (ImageView) ivOption.getChildAt(1);
iv.setImageResource(R.drawable.ic_radio_button_tick);*/
container.removeView(ll);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
public void refresh(ArrayList object) {
this.object = new ArrayList();
this.object.addAll(object);
this.notifyDataSetChanged();
}

How to set viewpager to change page automatically after 5 sec

i Want to make a slideshow with viewpager where pages are changed automatically every 5 sec. Ive done the viewpager , but got blocked till here , any advise??
Adapter.class (its inner class in my fragment)
class CustomPagerAdapter extends PagerAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
public CustomPagerAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#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 = mLayoutInflater.inflate(R.layout.slide_show_item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
}
Here is the function i call in my fragment
public void setSlideShow(){
mCustomPagerAdapter = new CustomPagerAdapter(getActivity());
mViewPager = (ViewPager)rootView.findViewById(R.id.slide_show);
mViewPager.setAdapter(mCustomPagerAdapter);
}
Well, android does not provide any function to automatically flip views inside ViewPager but it provides you with something called TimerTask class which you can use to achieve your goal.
You can look at this link to do it this way.
There is one more easy way to achieve this but for that you will have to drop the idea of using ViewPager. Instead you can use ViewFlipper.
ViewFlipper has its own methods to flip automatically. You just need to add these two lines to make your views automatically flippable:
mViewFlipper.setAutoStart(true);
mViewFlipper.setFlipInterval(2000); // flip every 2 seconds (2000ms)
You can get ViewFlipper example here.

How Do Implement ViewPager PagerTitleStrip?

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

add dynamic button to xml in viewpager

First, this is my MainPageViewer:
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager);
MyPageAdapter adapter = new MyPageAdapter();
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
pager.setCurrentItem(0);
The Adapter for my PageViewer is here:
public int getCount()
{
return 3;
}
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.blogandbericht;
break;
case 1:
resId = R.layout.blogandbericht;
break;
case 2:
resId = R.layout.blogandbericht;
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;
}
(Yes i know, that all layout are "bloganbericht")
And this my blogandbericht:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/masterSv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#8ad5f0">
<LinearLayout
android:id="#+id/masterLl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="foo bar"/>
</LinearLayout>
</ScrollView>
all works fine. I can see the three buttons on each layout.
But how can i add views like textview or button to the layout dynamicly?
Well the viewpager only supports 1 view inside each page, so in the adapter you modify the method:
public Object instantiateItem( View pager, int position )
you can create the view inside this method and return it to like this:
WebView web = new WebView(mContext);
return web;
Or if you need a more complex view than just an "Object" then you can create a linear layout, or something similar and add your other views inside and return that view like this:
LinearLayout layout = new LinearLayout(mContext);
WebView web = new WebView(mContext);
Button btn = new Button(mContext);
layout.addView(web);
layout.addView(btn);
return layout;
Hope it helps.
UPDATE:
Well right now i am doing something similar, i make the view that i will add to the viewpager dynamic, so depending on the type of an object i determine what is going to be inside.
I do not know how you plan to determine how a page must look, but i will tell you how i do it.
I have a list of "Objects", and those objects extends from a Class (You can also do it with interface and implementation, i do it with extends for other reasons) in common, and that class have a method "public View getView()" and the in all the Classes that extends from the Father Class (or Implemented the Interface), you Override (Implement) the method and add the code necessary to make that "PAGE" look like you want, then on the adapter you only need to have a list of "Objects" of any of the classes that you created and depending on which type each of those "Objects" are they will create the View passed to the ViewPager.
EXAMPLE:
Dog //CLASS OR INTERFACE WITH METHOD getView()
-Chihuahua //This return a WebView
-Sharpei //This return a HorizontalListView
-Huskie //This return a LinerLayout with a Bunch of Views Inside
on your adapter:
public class ViewPagerAdapter extends PagerAdapter {
List<Dog> Doggies = new ArrayList<Dog>();
public ViewPagerAdapter( Context context ){
Doggies.add(new Chihuahua());
Doggies.add(new Sharpei());
Doggies.add(new Chihuahua());
Doggies.add(new Huskie());
Doggies.add(new Huskie());
Doggies.add(new Chihuahua());
Doggies.add(new Sharpei());
}
//and last but not least, on your onCreate method in your adapter:
public Object instantiateItem( View pager, int position ){
return Doggies.get(position).getView();
}
/*THE REST OF THE METHODS GOES AFTER THIS*/
} //END OF ADAPTER

ViewPager doesn't update correct/ OnClickListener doesn't react

)
I implemented a ViewPager in my application, and seems to work well, I use 3 XML Files for the views. on the "settings_view" there are two EditText and one Button. The Button instantiates correct, because in Debugg Mode I can see that it's not null, but when I'm clicking on, nothing happens. To understand it better, here a code excerpt:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LayoutInflater getView = getLayoutInflater();
View pushview = getView.inflate(R.layout.push_view,null);
View listenView =getView.inflate(R.layout.listen_view, null);
View settingsView = getView.inflate(R.layout.settings_view, null);
login = (Button)settingsView.findViewById(R.id.ok_button1);
login_user=(EditText)settingsView.findViewById(R.id.user1);
login_pw=(EditText)settingsView.findViewById(R.id.pw1);
ViewPager myPager = (ViewPager)findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter();
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
do something
}
});
And here is my Pager Adapter:
class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 3;
}
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.settings_view;
break;
case 1:
resId = R.layout.push_view;
break;
case 2:
resId = R.layout.listen_view;
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;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
So I cannot really figure out why it doesn't work, because it instantiates correct but the Listener doesn't react.
Is somebody here to open my eyes ?
Thanks
Update:
These are the values I get when instantiate the Button with findviewbyid:
login=Button (id=8300....)
mAttachInfo=null
.
.
.
android.widget.Button#4050d490
Is mAttachInfo neccessary?
or something else not normal?
Update:
Ok found out, that if I'm setting up the onclick in XML and then using just the method in code, it works fine, but now it's the same Problem Spinner.setAdapter, nothing happens...
update: solved it with that link, it's briliant
http://code.google.com/p/ratebeerforandroid/source/browse/RateBeerForAndroid/src/com/ratebeer/android/gui/fragments/SearchFragment.java#486
I am implement onTouchListerner and then try to detect onclicklisterner.
You can refer my answer here:
https://stackoverflow.com/a/13264379/968532

Categories

Resources