我有一个viewpager,每个页面都包含一个数字
示例:
第1页包含textview文本" 1"
第2页包含textview文本" 2"
......再增加20个
然后我得到文字:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
TextView myText= adapter.getTextView();
CharSequence charSequence = dateArea.getText();
String dateString = charSequence.toString();
Log.e("TEST1", dateString);
}
}
当我单向滑动(向右或向左)时,它会正确显示文本。但当我向前滑动时,问题出现了:
示例:
我向左滑动(从10开始),结果为9(正确)。
然后我向右滑动,结果仍然是9(应该是10)。
然后我再次向左滑动,结果是9.此时,如果我再向左滑动一次,它将显示正确的结果,即8.请告诉我如何解决这个问题!
修改
public class ViewPagerAdapter extends PagerAdapter {
Context context;
LayoutInflater inflater;
String[] listNumber;
TextView textView;
public ViewPagerAdapter(Context context, String[] listNumber) {
this.context = context;
this.listNumber= listNumber;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
@Override
public Object instantiateItem(final ViewGroup container, final int position) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_adapter, container, false);
textView= (TextView) itemView.findViewById(R.id.textView);
textView.setText(listNumber[position]);
((ViewPager) container).addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listNumber.length;
}
public TextView getTextView() {
return textView;
}
}
答案 0 :(得分:1)
首先,通过将TextView设置为local:
来将适配器更改为此@Override
public Object instantiateItem(final ViewGroup container, final int position) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_adapter, container, false);
Textview textView= (TextView) itemView.findViewById(R.id.textView);
textView.setText(listNumber[position]);
textView.setTag("tv"+position);
((ViewPager) container).addView(itemView);
return itemView;
}
然后,您可以使用以下代码段在pagechange上获取textview。
。不再需要adapter.getTextView()mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
TextView myText= (TextView) mViewPager.findViewWithTag("tv"+ arg0);
mText.setText(dateString);
CharSequence charSequence = dateArea.getText();
String dateString = charSequence.toString();
Log.e("TEST1", dateString);
}
}