我是android编程的初学者。 我正在使用按钮onclick使用以下代码将新页面添加到viewpager。但是,当在滑动活动上实例化项目时,viewpager返回错误的位置值。
向右滑动
正确位置:1,2,3(第2,3和4页)
返回错误的位置:2,3,4
向左滑动
正确位置:3,2,1(第4页,第3页和第2页)
改为错误的位置:2,1,0
我想从instantiateItem()获取位置值,以便从"视图"中的特定位置获取视图。要在viewpager上显示的数组列表。错误的位置会导致显示错误的视图。希望可以有人帮帮我!!!提前谢谢。
添加按钮:
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.image_text_1, null);
// the array list
views.add(itemView);
pagerAdapter.notifyDataSetChanged();
}
});
ViewPager:
private class SlideAdapter extends PagerAdapter {
ArrayList<View> views = new ArrayList<View>();
@Override
public int getItemPosition (Object object)
{
int index = views.indexOf((View)object);
if(views.contains((View)object)){
return index;
}else{
return POSITION_NONE;
}
}
@Override
public Object instantiateItem (ViewGroup container, final int position)
{
//for example, when I swipe to the right from page 1 to page 2, the int position return value of 2 instead of 1.
View v = views.get(position);
imagePage = (ImageView) v.findViewById(R.id.imgSlide);
imagePage.setOnLongClickListener(null);
imagePage.setLongClickable(true);
imagePage.setOnLongClickListener(btnImageChoose);
((ViewPager)container).addView(v, 0);
return v;
}
@Override
public void destroyItem (ViewGroup container, int position, Object object)
{
container.removeView (views.get(position));
}
@Override
public int getCount ()
{
return views.size();
}
@Override
public boolean isViewFromObject (View view, Object object)
{
return view == object;
}
public int addView (View v)
{
return addView (v, views.size());
}
public int addView (View v, int position)
{
views.add (position, v);
return position;
}
public int removeView (ViewPager pager, View v)
{
return removeView (pager, views.indexOf (v));
}
public int removeView (ViewPager pager, int position)
{
pager.setAdapter (null);
views.remove (position);
pager.setAdapter (this);
return position;
}
public View getView (int position)
{
return views.get (position);
}
}
答案 0 :(得分:7)
似乎不是instantiateItem()问题。我从setPrimaryItem()获取当前视图。
private View mCurrentView;
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
mCurrentView = (View)object;
}
答案 1 :(得分:0)
您不需要使用视图数组列表:
class SamplePagerAdapter extends PagerAdapter {
// for example
List<String> str = new ArrayList<String>();
public SamplePagerAdapter(List<String> str){
this.str = str;
}
private void addPage(String item) {
str.add(item);
notifyDataSetChanged();
}
@Override
public int getCount() {
return str.size();
}
@Override
public View instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(container.getContext());
View v = inflater.inflate(R.layout.image_text_1, container, false);
// Your code. (don't use addView);
return v;
}
}
并在onClick方法中:
public void OnClick(View v){
adapter.addPage("New page")
}