jwBurnside jwBurnside - 4 months ago 14
Android Question

How do I keep track of an edittext field across PagerAdapter slides?

I'm using a fairly simple custom pager adapter in Android, and I'd like to keep track of the contents of the edittext fields so that each new slide retains the same text if entered. Anyone have any insight on this? I'm guessing I'll need to set up a listener for text change, but I'm unsure of where to put it. Here is my adapter:

private class CustomPagerAdapter extends PagerAdapter {

public int getCount() {
return 3;
}

public Object instantiateItem(ViewGroup collection, int position) {

LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View view;

switch(position) {
case 0:
view = inflater.inflate(R.layout.slide0, null, false);
break;
case 1:
view = inflater.inflate(R.layout.slide1, null, false);
break;
case 2:
view = inflater.inflate(R.layout.slide2, null, false);
break;
default:
view = inflater.inflate(R.layout.slide0, null, false);
}
collection.addView(view,0);

return view;
}



@Override
public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
arg0.removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public Parcelable saveState() {
return null;
}

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
mCurrentSlide = (View) object;

}
}

Answer

Ok, here is how I did it:

Set a member variable in your main class:

mText = "";

Set up a textWatcher in instantiateItem() in your adapter class:

EditText edtSlide = (EditText)view.findViewById(R.id.edtSlide);
//Set a listener for the editText that updates the member variable on keystroke.
    TextWatcher tw = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mText = s.toString();
        }

        };

    edtSlide.addTextChangedListener(tw);

Then in the setPrimaryItem() method in your adapter class:

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
    super.setPrimaryItem(container, position, object);
    EditText text = (EditText)((View) object).findViewById(R.id.edtSlide);
    text.setText(mText);
}